Time and Space Complexity
Use Big-O to estimate whether an approach fits the constraints, and read constraints to guess the intended solution before coding.
Beginner · about 5 hours · difficulty 2/5
Learn first: How Campus and Off-Campus Hiring Works
Complexity analysis tells you, before you code, whether a solution will pass. Interviewers ask for it after every problem, so you must state it without hesitation.
Big-O basics
- Count how work grows with input size n, dropping constants and lower-order terms.
- Common classes: O(1), O(log n), O(n), O(n log n), O(n^2), O(2^n), O(n!).
- Nested loops multiply, sequential steps add. A loop that halves n each time is O(log n).
- Space counts extra memory, including the recursion stack.
Read the constraints
A judge does roughly 1e8 simple operations per second. Use this table:
- n up to 10 to 12: O(n!) or O(2^n * n) (permutations, bitmask brute force)
- n up to 20 to 25: O(2^n)
- n up to 500: O(n^3)
- n up to 5000: O(n^2)
- n up to 1e5 to 1e6: O(n log n) or O(n)
- n up to 1e9 or more: O(log n) or O(1) (math, binary search)
Amortised and recursive cost
Dynamic array push is O(1) amortised. Recursion cost is (number of calls) x (work per call): naive Fibonacci is O(2^n), merge sort is O(n log n) by the recurrence T(n) = 2T(n/2) + O(n).
Pitfalls
- Forgetting hidden costs: string concatenation, slicing,
substrand copying inside loops. - Calling an O(n) operation like
list.indexinside a loop and calling the result O(n).
You are ready to move on when you can look at a constraint like n = 2e5 and immediately say "I need O(n log n) or better".
Key concepts
- Big-O, Big-Omega, Big-Theta
- Common complexity classes
- Space complexity and recursion stack
- Reading constraints to pick an approach
- Amortised analysis
- Recurrences and Master theorem
- Best, average and worst case
Mini project
Take 15 code snippets from your old assignments or LeetCode discussions, write the time and space complexity of each, then verify 5 of them by timing them on inputs of size 1e3, 1e4 and 1e5.
Check yourself
A problem has n up to 2e5. Your solution has two nested loops over n. Will it pass, and what complexity should you aim for?
Free resources
- Big-O Cheat Sheet (bigocheatsheet)
- Competitive Programmer's Handbook (Ch. 2) (CSES)
- USACO Guide (USACO Guide)