Note_Tech

All technological notes.


Project maintained by simonangel-fong Hosted on GitHub Pages — Theme by mattgraham

DSA - Big O

Back


Big O Notation


Space Complexity


Best Case, Average Case, and Worst Case

Geek Letter Notation
Ω(Omiga) Best Case
θ(theta ) Average Case
O(Omikron) Worst Case

Common Big-O

Big-O Name
O(1) Constant
O(log(n)) Logarithmic
O(n) Linear
O(nlog(n)) Log Linear
O(n^2) Quadratic
O(2^n) Exponential

diagram


O(n): Linear / Proportional

def print_items(n):
    '''
    Takes n operations for a specific input n
    '''
    for i in range(n):
        print(i)

func_lin(10)


O(n^2): Quadratic / Loop within a loop


def print_items(lst):
    for i in range(n):
        for j in range(n):
            print(i, j)

print_items(10)

O(1): Constant

def add_items(n):
    return n + n + n

add_items(10)

O(log(n)): Divide and Conquer


Big O Analysis

Drop Constants

def print_items(n):
    for i in range(n):
        print(i)

    for j in range(n):
        print(j)

print_items(10)
# 对每个operation都执行两次, 所以time complexity是O(2n), 分析时看作是O(n)


Drop Non-Dominants

def print_items(n):
  # O(n^2)
    for i in range(n):
        for j in range(n):
            print(i,j)

  # O(n)
    for k in range(n):
        print(k)

print_items(10)

Different Terms for Inputs

def print_items(a,b):
    for i in range(a):
        print(i)

    for j in range(b):
        print(j)

print_items(1, 10)

Big O of List

Operation Big O Description
.append() O(1)  
.pop() O(1)  
.insert(0,value) O(n) re-indexing
.pop(0) O(n) re-indexing
list[index] O(1) look for value with index

Big-O Cheat Sheet

Big-O Cheat Sheet


TOP