Time/Space Complexity Flashcards
O(1)
Constant time. Most efficient algo
Big O of pop/remove from hashmap
O(1)
Big O of lookup in hashmap
O(1)
Big O of search an array
Worse case: O(n)
Might have to go through entire array to find
Big O of insert into hashmap
O(1)
Big O of loop through an array
O(n)
Big O of push/pop from array
O(1)
What is O(log n)
Binary search.
On every iteration of loop, we halve the remaining elements and search again
What is O(n^3)
3-D data structure. Get triplets of loops
What is O(n * m)
2-D array that’s not a perfect square (ex. 2x3 grid)
Big O of getting length of list
O(1)
Big O deque vs. list
Index access:
- Deque: O(n)
- List: O(1)
Pop from right:
- Deque: O(1)
- List O(1)
Pop from left:
- Deque: O(1)
- List: O(n)
Big O of sum an array
O(n)
What is O(n!)
Permutations
Ex. traveling salesman
What is O(n log n)
Heap sort, merge sort
What is O(2^n)
Recursion, with tree height of n and 2 branches.
Can be 4^n, 5^n, etc. Depends on how many loops for recursion
Sort a list
O(n log n)
What is O(n^2)
Traverse a square grid. Get every pair of elements in an array
Big O of remove/insert from middle of array
Worse case: O(n) since values have to be moved around
What is O(n)
Linear growth/time. As input grows, so does time
Big O of lookup in array
O(1)
Difference between O(n + m) and O(n * m)
O(m+n) example:
for(int i = 0, i < m, i++)
//code
for(int j = 0, j < n, j++)
//code
m iterations of code happen. Then n iterations of code happens.
O(mn) example:
for(int i = 0, i < m, i++)
for(int j = 0, j < n, j++)
//code
For every iteration of m, we have n iterations of code. Imagine iterating over a non-square 2D array.
m and n do not necessarily equal the same value. If they did equal the same value, then for O(m+n):
O(m+n) => O(m+m) => O(2m) => O(m)
When to add vs multiply for Big O setup
Add different complete instructions (loop through a, when done with all, loop through b)
Multiple if nested loop
Big O of list extend()
The extend() operation here is O(k) where k=4 (the size of list2).
list1 = [1, 2, 3]
list2 = [4, 5, 6, 7]
list1.extend(list2)