What Is Big‑O Notation?
Big‑O is a way to describe how the running time (or memory usage) of an algorithm grows as the size of its input gets larger.
Instead of giving an exact number of seconds, we talk about the trend:
- O(1) – constant time: the work doesn’t change with input size.
- O(log n) – logarithmic: each step cuts the problem size roughly in half.
- O(n) – linear: work grows proportionally to the number of items.
- O(n log n) – linear‑logarithmic: common for efficient sorting.
- O(n²) – quadratic: work grows with the square of the input size (e.g., nested loops).
The “O” stands for “order of”. It tells you the upper bound on how bad the algorithm can get.
Why Does It Matter?
- Predict performance – Know whether an algorithm will stay fast as data grows.
- Compare alternatives – Choose a faster algorithm for large inputs.
- Interview language – Many coding interviews ask you to state the Big‑O of your solution.
Simple, Code‑First Example
1️⃣ Linear Scan (O(n))
- The loop looks at each element once.
- If the array has
nitems, the worst‑case work is proportional ton→ O(n).
2️⃣ Nested Loops (O(n²))
- For each of the
nelements, we run another loop ofniterations. - Total work ≈
n × n→ O(n²).
3️⃣ Binary Search (O(log n))
- Each step cuts the searchable range in half.
- After about
log₂ nsteps we either find the target or run out of range → O(log n).
Quick Cheat Sheet
| Complexity | Typical Pattern | Example |
|---|---|---|
| O(1) | Direct access, fixed work | arr[0], return 42 |
| O(log n) | Divide‑and‑conquer, halving | Binary search, tree lookup |
| O(n) | Single loop over input | Linear scan, summing an array |
| O(n log n) | Efficient sort, divide‑and‑conquer | Merge sort, heap sort |
| O(n²) | Double nested loops | Comparing every pair of items |
| O(2ⁿ) | Exhaustive search of subsets | Solving the traveling salesman naïvely |
Bottom Line
- Big‑O tells you the growth rate, not the exact time.
- It helps you pick algorithms that stay fast when your data grows.
- Look at the structure of your code (loops, recursion, halving) to guess the Big‑O.
Happy coding!