Authored by Tony Feng
Created on March 17th, 2022
Last Modified on March 18th, 2022
Time Complexity
Def
- The efficiency of the algorithm
- The relationship between the algorithm’s input and its execution time
Common Cases
- O(1)
|
|
- O(n)
|
|
- O(m+n)
|
|
- O(log(n))
|
|
- O(n*log(n))
|
|
- O(n2)
|
|
Comparison
- O(1) < O(log(n)) < O(n) < O(n*log(n)) < O(n2) < O(2n) < O(n!)
Space Complexity
Def
- The relationship between the algorithm’s input and its memory space needed
Common Cases
- O(1)
|
|
- O(n)
|
|
Analysis Approches
-
Check the variable
-
If the variable varies in response to the input, e.g. array, linked list, hash map, etc., the space complexity may be O(n), O(n2) …
-
If not, it is O(1)
-
Determine the space complexity case-by-case.
-
Be careful with the recursion. Info in each level are stored on a recursive stack.
Summary
- There is a trade-off between time and space.
- Time should be considered in the first place.