All technological notes.
Analyze algorithms
Big-O notation
Remember, we want to compare how quickly runtime will grows, not compare exact runtimes, since those can vary depending on hardware.
Since we want to compare for a variety of input sizes, we are only concerned with runtime grow relative to the input. This is why we use n for notation.
As n gets arbitrarily large we only worry about terms that will grow the fastest as n gets large, to this point.
Big-O analysis is also known as asymptotic analysis| Geek Letter | Notation |
|---|---|
Ω(Omiga) |
Best Case |
θ(theta ) |
Average Case |
O(Omikron) |
Worst Case |
big O, it is usually talking about worst case.| 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 |

Clearly we want to choose algorithms that stay away from any exponential, quadratic, or cubic behavior!
When it comes to Big O notation we only care about the most significant terms, remember as the input grows larger only the fastest growing terms will matter.
O(n): Linear / ProportionalThe function runs in O(n) (linear time).
图像上, 随着n的增加, number of operationO(n)呈现线性增长.
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 loopThe function performs n operations for every item in the list!
n times n assignments, or n^2.O(n*n) = O(n^2)
def print_items(lst):
for i in range(n):
for j in range(n):
print(i, j)
print_items(10)
O(1): ConstantBig Odef add_items(n):
return n + n + n
add_items(10)
O(log(n)): Divide and Conquer简化的推导过程:
Big O = log(n), 注意该处 log 的底是 2.Big O(worst case)2^Big(O) => Big O = log(n) => O(log(n))A very efficient Big O. Flat and close to O(1)
Drop Constants
O(n) + O(n) = O(n+n) = O(2n) = O(n)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
O(n^2) + O(n) = O(n^2 + n) = O(n^2)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)
Big O是O(a)+O(b) = O(a+b), 不能再简化.因为参数有两个, 不能直接简化为O(2n)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是O(a)*O(b) = O(a*b)List is a built-in data structure in Python.
O(1)O(n)O(1)| 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 |
Common Data Structure
O(n), 所以现实中一般注重 time 复杂度.

Array Sorting Algorithms
