Time & Space Complexity
Big-O in one minute
Section titled “Big-O in one minute”Big-O describes how the running time or memory grows as the input grows. We keep the term that grows fastest and drop constants.
3n + 5→ O(n)n² + n→ O(n²)n + mwith two different inputs → O(n + m). Don’t merge them into O(n).
Big-O is usually the worst case. If someone asks about the average case (like HashMap lookups or quicksort), say so out loud.
Common complexities
Section titled “Common complexities”| Complexity | Name | Example | n = 10^5 feasible? |
|---|---|---|---|
| O(1) | Constant | Array index, HashMap get | Yes |
| O(log n) | Logarithmic | Binary search, heap push/pop | Yes |
| O(n) | Linear | One loop, two pointers | Yes |
| O(n log n) | Linearithmic | Sorting, n heap operations | Yes |
| O(n²) | Quadratic | Nested loops over all pairs | No (10^10) |
| O(2^n) | Exponential | All subsets | Only n ≤ ~20 |
| O(n!) | Factorial | All permutations | Only n ≤ ~10 |
Analyzing loops
Section titled “Analyzing loops”// O(n): single loopfor (int i = 0; i < n; i++) { ... }
// O(n^2): nested loops, each up to nfor (int i = 0; i < n; i++) for (int j = i + 1; j < n; j++) { ... } // n(n-1)/2 is still O(n^2)
// O(log n): the variable doubles or halves each timefor (int i = 1; i < n; i *= 2) { ... }
// O(n log n): an outer n loop with an inner log n loopfor (int i = 0; i < n; i++) for (int j = 1; j < n; j *= 2) { ... }
// O(n + m): loops one after another ADDfor (int i = 0; i < n; i++) { ... }for (int j = 0; j < m; j++) { ... }Trap: the sliding window looks like a nested loop but is O(n). The inner pointer only moves forward, so across the whole run it moves at most n times. Say this out loud: “Each element is added and removed at most once, so it’s O(n) amortized.”
Analyzing recursion
Section titled “Analyzing recursion”Time is roughly (number of calls) × (work per call). A quick way to see it is to draw the recursion tree.
| Recurrence | Example | Result |
|---|---|---|
| T(n) = T(n-1) + O(1) | Factorial, linked list recursion | O(n) |
| T(n) = T(n/2) + O(1) | Binary search | O(log n) |
| T(n) = 2T(n/2) + O(n) | Merge sort | O(n log n) |
| T(n) = 2T(n-1) + O(1) | Naive Fibonacci, subsets | O(2^n) |
| T(n) = 2T(n/2) + O(1) | Tree traversal | O(n) |
Memoization changes the count: naive Fibonacci is O(2^n), but with a memo each fib(i) runs once, so it becomes O(n).
Space complexity
Section titled “Space complexity”Count the extra memory you use. The input usually doesn’t count, but the output sometimes does, so mention it.
- Variables only → O(1)
- A HashMap/array sized by the input → O(n)
- A 2D DP table → O(n·m)
- The recursion stack counts! Recursion depth d means O(d) space.
- DFS on a balanced tree → O(log n). On a skewed tree → O(n).
- Naive recursive Fibonacci → depth n → O(n) space, even though nothing is stored.
Java collections cost table
Section titled “Java collections cost table”| Structure | Operation | Cost |
|---|---|---|
int[] / ArrayList |
get(i), set(i) | O(1) |
ArrayList |
add(x) at end | O(1) amortized |
ArrayList |
add(i, x) / remove(i) in middle | O(n) |
ArrayList |
contains(x) | O(n) |
LinkedList |
addFirst / addLast / removeFirst | O(1) |
LinkedList |
get(i) | O(n) |
HashMap / HashSet |
put, get, remove, contains | O(1) average, O(n) worst (O(log n) for big buckets since Java 8) |
TreeMap / TreeSet |
put, get, remove, floorKey, ceilingKey | O(log n) |
PriorityQueue |
offer, poll | O(log n) |
PriorityQueue |
peek | O(1) |
PriorityQueue |
remove(Object), contains | O(n) |
ArrayDeque |
push/pop/offer/poll/peek (both ends) | O(1) amortized |
Arrays.sort(int[]) |
primitives (dual-pivot quicksort) | O(n log n) average |
Arrays.sort(Object[]) / Collections.sort |
TimSort, stable | O(n log n) |
String |
+ in a loop |
O(n²) total, so use StringBuilder |
String |
substring, toCharArray | O(k) / O(n) |
StringBuilder |
append | O(1) amortized |
Amortized analysis: ArrayList.add
Section titled “Amortized analysis: ArrayList.add”An ArrayList is backed by an array. When it’s full, Java creates a bigger array (about 1.5×) and copies everything over. That single add is O(n).
So why is add O(1)? Amortized: averaged over many adds. With doubling, inserting n elements causes copies of 1 + 2 + 4 + … + n ≈ 2n elements in total. So n adds cost O(n) total, which is O(1) per add on average. (Growing by 1.5× instead of 2× only changes the constant.)
How to say it: “A single add can be O(n) when it resizes, but resizes get rarer as the array grows, so over n operations it averages out to O(1) each.”
The same idea applies to HashMap rehashing, StringBuilder.append, and the monotonic stack (each element is pushed and popped once).
How to state complexity in the interview
Section titled “How to state complexity in the interview”“Time is O(n log n). Sorting dominates, and after that it’s a single O(n) pass. Space is O(n) for the hash map. If we don’t count the output, the rest is O(1).”