Big O Notation: The Developer's Practical Guide
Big O is how you talk about algorithm efficiency in interviews. Here's what each notation means and how to analyse code on the spot.
Big O describes how an algorithm's time or space requirements grow as input size grows. In interviews, you're expected to state complexity for every solution you write.
The common complexities
| Big O | Name | Example | 1M input |
|---|---|---|---|
| O(1) | Constant | Hash map lookup | ~1ns |
| O(log n) | Logarithmic | Binary search | ~20 ops |
| O(n) | Linear | Array scan | ~1M ops |
| O(n log n) | Linearithmic | Merge sort | ~20M ops |
| O(nΒ²) | Quadratic | Bubble sort | ~1T ops |
| O(2βΏ) | Exponential | Recursive Fibonacci | never |
How to analyse code
Rule 1: Drop constants
// O(2n) β O(n)
for (int x : arr) { process(x); } // n
for (int x : arr) { log(x); } // n
Rule 2: Drop non-dominant terms
// O(nΒ² + n) β O(nΒ²)
for (int i : arr) // n
for (int j : arr) { ... } // nΒ²
Rule 3: Different inputs = different variables
// O(a + b), NOT O(n)
void foo(int[] a, int[] b) {
for (int x : a) { ... } // a
for (int x : b) { ... } // b
}
Rule 4: Recursion = check the recurrence
Fibonacci naive: each call branches into two β O(2βΏ) Fibonacci memoized: each value computed once β O(n)
Space complexity
Space complexity measures additional memory used, not the input itself.
- Iterative array algorithm with a hash map: O(n) space
- Recursive DFS on a tree of height h: O(h) stack space
- In-place sorting: O(1) space
Interview tip
State complexity proactively: "This is O(n log n) time and O(1) space." Then the interviewer knows you know β they don't have to ask.
Related Posts
The Sliding Window Pattern: One Template, Many Problems
Turn O(nΒ²) substring and subarray problems into O(n). The fixed and variable sliding window templates in Java, with six worked interview problems.
14 Coding Patterns That Solve 80% of Interview Problems
Instead of memorising 500 LeetCode solutions, learn 14 patterns. Recognise the pattern and you can derive the solution from first principles.