If you're learning Data Structures & Algorithms (DSA), Big O notation is the very first concept you need to get comfortable with. It looks intimidating at first — O(n log n)? O(2^n)? — but the idea behind it is actually simple. This guide breaks it down with everyday analogies and JavaScript examples.
What Is Big O Notation?
Big O notation describes how the runtime or memory usage of an algorithm grows as the input size (n) grows. It doesn't tell you the exact number of seconds or bytes — it tells you the trend: does the work double when the input doubles? Quadruple? Stay the same?
Think of it like this: if you're searching for a name in a phone book, does doubling the number of pages double how long you search (bad), or barely change it at all (great)? Big O is how we describe that relationship in a single, comparable label.
The Complexities You'll See Most Often
O(1)– Constant time. Same speed no matter how big the input is.function getFirst(arr) { return arr[0]; // always 1 step }O(log n)– Logarithmic time. The work shrinks by half each step (binary search is the classic example).O(n)– Linear time. Work grows in direct proportion to input size.function findMax(arr) { let max = arr[0]; for (let i = 1; i < arr.length; i++) { if (arr[i] > max) max = arr[i]; } return max; // 1 pass through the array }O(n log n)– Linearithmic time. Common in efficient sorting algorithms like merge sort and quick sort.O(n²)– Quadratic time. Usually caused by nested loops over the same input.function hasDuplicate(arr) { for (let i = 0; i < arr.length; i++) { for (let j = i + 1; j < arr.length; j++) { if (arr[i] === arr[j]) return true; } } return false; // n items checked against n items }O(2^n)– Exponential time. Work doubles with every additional input item — gets unusable very fast (e.g., naive recursive Fibonacci).
Why It Matters
Two functions can produce the same correct output but behave completely differently at scale. An O(n²) function might run instantly on 10 items and take minutes on 100,000. Big O is how you catch that before it becomes a production problem — and it's one of the most common things interviewers ask you to reason about out loud.
Quick Reference: Best to Worst
O(1) < O(log n) < O(n) < O(n log n) < O(n²) < O(2^n) < O(n!)
Conclusion
Big O notation is just a vocabulary for talking about how algorithms scale. Once you can recognize O(1), O(n), and O(n²) patterns in your own code, the rest of DSA — sorting, searching, data structures — becomes much easier to reason about. Next up in this series: Arrays vs Linked Lists.
Image: Cmglee / Wikimedia Commons (CC BY-SA 4.0)
Comments
Post a Comment