Big O Notation Explained: Time and Space Complexity for Beginners
Understand Big O notation with simple examples: O(1), O(log n), O(n), O(n log n), O(n²) and O(2ⁿ), how to calculate complexity from code, space complexity, amortized analysis and common data structure costs.
Big O notation describes how the running time or memory of an algorithm grows as the input gets bigger. It doesn't measure seconds. Instead, it answers "if I double the input, how much more work does this do?" That's why it's the common language for comparing algorithms in interviews and code reviews.
Why not just time the code?#
Actual run time depends on your machine, language, compiler and what else is running. Big O ignores those details and focuses on the growth rate. An O(n²) algorithm might be fast for 100 items, but for 1,000,000 items it will lose to an O(n log n) algorithm on any computer.
The common complexity classes#
| Big O | Name | n = 1,000 | Example |
|---|---|---|---|
| O(1) | Constant | 1 | Array index, hash map lookup |
| O(log n) | Logarithmic | ~10 | Binary search |
| O(n) | Linear | 1,000 | Loop through a list |
| O(n log n) | Linearithmic | ~10,000 | Merge sort, efficient sorting |
| O(n²) | Quadratic | 1,000,000 | Nested loops over the same data |
| O(2ⁿ) | Exponential | astronomical | All subsets, naive recursion |
| O(n!) | Factorial | astronomical | All permutations |
O(1): constant time#
def get_first(items):
return items[0] # one step, no matter how long the list is
prices = {"apple": 120}
prices["apple"] # average O(1) hash lookupO(log n): logarithmic time#
Each step cuts the problem in half. Doubling the input adds just one more step.
def count_halvings(n):
steps = 0
while n > 1:
n //= 2
steps += 1
return steps # count_halvings(1_000_000) == 19See binary search for the classic O(log n) algorithm.
O(n): linear time#
def find_max(nums):
best = nums[0]
for x in nums: # touches every element once
if x > best:
best = x
return bestO(n log n): linearithmic time#
def merge_sort(a):
if len(a) <= 1:
return a
mid = len(a) // 2
left, right = merge_sort(a[:mid]), merge_sort(a[mid:]) # log n levels
merged, i, j = [], 0, 0
while i < len(left) and j < len(right): # n work per level
if left[i] <= right[j]:
merged.append(left[i]); i += 1
else:
merged.append(right[j]); j += 1
return merged + left[i:] + right[j:]Most good sorting algorithms (merge sort, heap sort, Python's Timsort, Java's sort for objects) are O(n log n).
O(n²): quadratic time#
def has_duplicate_slow(nums):
for i in range(len(nums)):
for j in range(i + 1, len(nums)): # nested loop over the same data
if nums[i] == nums[j]:
return True
return False
def has_duplicate_fast(nums): # O(n) with a set
return len(set(nums)) != len(nums)O(2ⁿ): exponential time#
def fib(n):
if n < 2:
return n
return fib(n - 1) + fib(n - 2) # each call branches into two
from functools import lru_cache
@lru_cache(maxsize=None)
def fib_memo(n): # memoization → O(n)
return n if n < 2 else fib_memo(n - 1) + fib_memo(n - 2)fib(40) makes over 300 million calls; fib_memo(40) makes 41. Spotting and removing repeated work like this is the heart of dynamic programming.
How to calculate Big O#
Rule 1: drop constants#
for x in nums: print(x) # n
for x in nums: print(x * 2) # n
# total 2n → O(n)Rule 2: keep only the dominant term#
O(n² + n + 100) becomes O(n²), because for large n the n² term swamps the rest.
Rule 3: sequential steps add, nested steps multiply#
for a in A: # O(a)
pass
for b in B: # O(b) → together O(a + b)
pass
for a in A:
for b in B: # O(a × b)
passIf a function loops over two different arrays, the answer is O(a + b) or O(a·b), not O(n) or O(n²). Using one letter for both is a common interview mistake.
Rule 4: watch for hidden loops#
for word in words:
if word in banned_list: # 'in' on a list is O(m) → whole loop is O(n·m)
...
result = ""
for s in parts:
result += s # string concatenation copies → can be O(n²)
"".join(parts) # O(n)Library calls like list.index, list.remove, slicing and sorted all have their own cost.
Rule 5: recursion = calls × work per call#
| Recursion pattern | Complexity |
|---|---|
| One call on n − 1, O(1) work | O(n) |
| One call on n / 2, O(1) work | O(log n) |
| Two calls on n / 2, O(n) work (merge sort) | O(n log n) |
| Two calls on n − 1, O(1) work (naive Fibonacci) | O(2ⁿ) |
Space complexity#
Space complexity measures extra memory used, excluding the input.
def total(nums): # O(1) space: one variable
s = 0
for x in nums:
s += x
return s
def squares(nums): # O(n) space: a new list
return [x * x for x in nums]
def depth(n): # O(n) space: n stack frames
return 0 if n == 0 else 1 + depth(n - 1)Recursion depth counts as space. This is why the recursive linked list reversal uses O(n) space while the iterative version uses O(1).
Best, average and worst case#
- Quick sort: O(n log n) on average, O(n²) in the worst case (bad pivots).
- Hash map lookup: O(1) on average, O(n) in the worst case (many collisions).
- Linear search: O(1) best case (first item), O(n) worst case.
When people say "Big O", they usually mean the worst case unless they say otherwise.
Amortized complexity#
A dynamic array (Python list, Java ArrayList) occasionally has to copy everything into a bigger array, which is O(n). But it doubles in size each time, so those copies are rare. Averaged over many appends, each append costs O(1). This is called amortized O(1).
Cheat sheet: common operations#
| Structure | Access | Search | Insert | Delete |
|---|---|---|---|---|
| Array / list | O(1) | O(n) | O(n) (O(1) amortized at end) | O(n) |
| Linked list | O(n) | O(n) | O(1) at known node | O(1) at known node |
| Hash map / set | n/a | O(1) avg | O(1) avg | O(1) avg |
| Balanced BST (TreeMap) | O(log n) | O(log n) | O(log n) | O(log n) |
| Binary heap | O(1) min/max | O(n) | O(log n) | O(log n) |
| Stack / queue | O(1) top/front | O(n) | O(1) | O(1) |
What input size can you handle?#
A typical judge runs about 10⁸ simple operations per second. Use the input limits to guess the required complexity:
| n up to | Target complexity |
|---|---|
| 10–12 | O(n!) |
| 20–25 | O(2ⁿ) |
| 500 | O(n³) |
| 5,000 | O(n²) |
| 10⁶ | O(n log n) |
| 10⁸ | O(n) or O(log n) |
Always state the time and space complexity of your solution before the interviewer asks. Then ask yourself whether a hash map, sorting, two pointers or a sliding window could bring it down a level.
Key takeaways#
- Big O describes how work grows with input size, not actual seconds.
- From fastest to slowest: O(1), O(log n), O(n), O(n log n), O(n²), O(2ⁿ), O(n!).
- Drop constants and smaller terms; add sequential steps and multiply nested ones.
- Count hidden costs in library calls and recursion depth for space.
- Use input limits to predict the complexity a problem expects.