Time and Space Complexity
Complexity describes how the running time (or memory) of an algorithm grows with the input size n. We use Big-O notation to describe the upper bound while ignoring constants.
Common growth rates
| Notation | Name | Example |
|---|---|---|
O(1) | Constant | Array index lookup, hash table get |
O(log n) | Logarithmic | Binary search |
O(n) | Linear | Scan a list once |
O(n log n) | Linearithmic | Merge sort, heap sort |
O(n²) | Quadratic | Nested loops, bubble sort |
O(2ⁿ) | Exponential | Naive Fibonacci, subsets |
O(n!) | Factorial | Permutations |
Counting operations
sum_pairs.py
def has_pair_with_sum(nums, target):
seen = set() # O(n) extra space
for x in nums: # n iterations
if target - x in seen: # O(1) average lookup
return True
seen.add(x)
return False # Time O(n), Space O(n)
Rules of thumb
- Drop constants:
O(2n)isO(n). - Keep the dominant term:
O(n² + n)isO(n²). - Sequential steps add; nested steps multiply.
- Recursion: count the number of calls times the work per call.
Best, average and worst case
Quick sort is O(n log n) on average but O(n²) in the worst case (already sorted input with a poor pivot). Always say which case you mean.
Loading Comments...