Big O
A way to describe how much slower or bigger a program gets as its input grows.
What is it?
Two solutions can both "work" but behave very differently as data grows. One stays fast with a million items; another grinds to a halt.
Big O notation describes that growth: how the time (or memory) a program needs scales as the input gets bigger, regardless of hardware.
You'll see it written like O(1), O(n), or O(n²), where n is the size of the input.
Explain like I'm 10
Looking up a word in a dictionary is fast, even in a huge dictionary. Checking every page one by one gets much slower as the dictionary grows. Big O describes that difference.
Examples
O(1) vs O(n)
// O(1) — constant time: same speed no matter the array size
function getFirst(arr) {
return arr[0];
}
// O(n) — linear time: gets slower as the array grows
function findValue(arr, target) {
for (let i = 0; i < arr.length; i++) {
if (arr[i] === target) return i;
}
return -1;
}getFirst always does one step. findValue may check every item, so its worst-case work grows with the array's size.
How it works
Big O describes the shape of growth and ignores constant factors.
O(1): the work stays the same whatever the input size.O(n): the work grows in step with the input.O(n²): the work grows with the square of the input, often from a loop nested inside another loop over the same data.
Input size (n) grows →
O(1) ▬▬▬▬▬▬▬▬▬▬ (flat — stays fast)
O(n) ▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬ (grows steadily)
O(n²) ▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬ (grows steeply)Why does it exist?
With thousands or millions of items, an efficient approach is the difference between an app that feels instant and one that freezes. Big O gives engineers a shared way to compare approaches before writing code, or while debugging it.
When to use it
Use Big O to compare how two approaches will scale, or to explain in an interview or code review why one solution is better.
When not to use it
For tiny, fixed-size inputs that never grow, O(n) versus O(n²) may not matter. Don't let Big O become premature optimization.
Common mistakes
Assuming code that works on a small test array will work at real scale.
Confusing best case with worst case. Big O usually describes the worst case.
Missing nested loops over the same data, one of the most common causes of O(n²) code.
Practice exercises
- Easy:
What is the Big O of a function that returns
array.length? - Medium:
What is the Big O of a function with one loop that checks every item in an array? Explain why.
- Hard:
What is the Big O of a function with a loop inside a loop, both over the same array? Explain what causes the extra cost.
Interview questions
What does Big O notation measure?
How an algorithm's running time or memory use grows as the input grows, regardless of hardware.
What's the difference between O(n) and O(n²)?
O(n) work grows in step with input size. O(n²) work grows with its square, usually from a loop nested inside another loop over the same input.
Is Big O about the best case or the worst case?
Usually the worst case, since that's the guarantee you can rely on. Best-case and average-case notations exist too.
Why is `O(2n)` simply written as `O(n)` in Big O notation?
Big O describes the shape of growth, not exact runtime. Multiplying by a constant like 2 doesn't change whether growth is flat, linear or quadratic, so constants are dropped.
Why is `O(n² + n)` simplified to just `O(n²)`?
As n gets large, n² grows so much faster than n that the n term becomes negligible. Big O keeps only the dominant (fastest-growing) term.
What is `O(log n)`, and what kind of code produces it?
Logarithmic time: work grows very slowly with n, because each step eliminates a large fraction (often half) of the remaining input. Doubling the input adds only about one extra step.
Why is binary search `O(log n)`?
Each comparison with the middle element eliminates half the remaining search space. After k comparisons, n / 2^k elements remain. That reaches 1 when k = log2(n).
What is `O(n log n)`, and where does it typically show up?
It's the cost of efficient comparison-based sorts like merge sort (always) and quicksort (on average). The data is split in half log n times, and each level does about n work merging or partitioning: n × log n.
What causes an algorithm to be `O(2ⁿ)`, and what's a classic example?
Usually a recursive function where each call branches into several more calls that redo work instead of reusing it. The classic example is naive recursive Fibonacci: fib(n) calls fib(n-1) and fib(n-2), roughly doubling the calls at each level.
What is `O(n!)`, and when does it come up?
Factorial time, which grows even faster than exponential. It shows up when you must consider every possible ordering (permutation) of n items, since there are n! of them.
What's the difference between time complexity and space complexity?
Time complexity is how running time grows with input size. Space complexity is how much extra memory is needed as input grows. They're measured independently: an algorithm can be fast but memory-hungry, or slow but memory-efficient.
When an interviewer asks for an algorithm's space complexity, does that include the input itself?
Usually not. Interviewers typically mean auxiliary space: extra memory beyond the input, such as temporary variables, new data structures or recursion stack frames.
What does `O(1)` space mean, and what's an example?
The extra memory used stays constant however large the input grows. Swapping two variables with a temporary, or a loop that tracks only a running total and an index, are both O(1) space.
Why can a recursive function have hidden space costs even if it doesn't create any new arrays or objects?
Each recursive call adds a frame to the call stack. Recursing to depth n means n frames in memory at once, so recursion depth alone can make an algorithm O(n) space.
A recursive factorial function and an iterative loop-based one are both `O(n)` time — are they equal in space complexity too?
No. The iterative version uses O(1) extra space: a counter and a running result. The recursive version uses O(n), because all n calls stay on the call stack until the base case returns.
What is the time complexity of `for (let i = 0; i < n; i++) { for (let j = 0; j < n; j++) { total++; } }`?
O(n²). The inner loop runs n times for each of the n outer iterations: n × n = n².
What is the time complexity of running two separate, non-nested loops back to back, each looping from `0` to `n`?
O(n). The loops aren't nested, so the total is n + n = 2n, and Big O drops the constant. It's not O(n²).
Is `array.push()` always `O(1)`? What's happening when it occasionally seems slower?
It's amortized O(1). Most pushes write to the next open slot: O(1). When the underlying capacity is full, the engine allocates a bigger block and copies every element: O(n) for that push. Capacity usually doubles, so resizes get rarer and the average cost per push stays O(1).
If a loop runs `n` times, and each iteration calls `array.includes()` (itself O(n)) on an array of size n, what's the overall time complexity — and why is it not just O(n)?
O(n²). Counting only the outer loop ignores the work inside each iteration. Each of the n iterations does O(n) work: n × n = O(n²).
If an outer loop runs `n` times but its nested inner loop always runs exactly 5 times regardless of `n`, what's the overall time complexity?
O(n). The inner loop doesn't depend on n, so it's a constant factor (5×) that gets dropped.
For a nested loop where the inner loop is `for (let j = i; j < n; j++)` inside an outer `for (let i = 0; i < n; i++)`, what's the time complexity, even though the inner loop gets shorter each pass?
Still O(n²). The inner loop runs n + (n-1) + ... + 1 = n(n+1)/2 times in total. That's quadratic, and Big O keeps only the n² term.
Why is a hash table lookup typically `O(1)` while searching an array for a value is `O(n)`?
An array search doesn't know where a value is, so it may check every element. A hash table computes an index from the key with a hash function and jumps straight to that slot. It trades extra memory for that speed.
Is a hash table lookup guaranteed to be `O(1)`?
Only on average, with a good hash function that spreads keys evenly. If many keys land in the same bucket (lots of collisions), lookup degrades toward O(n), since it must scan every entry in that bucket.
If most everyday programs run on fast hardware, why do interviewers care so much about Big O?
Real systems often handle thousands to billions of records. There, O(n log n) versus O(n²) can mean milliseconds versus hours on the same hardware. Big O predicts which approach holds up as data grows, which is where production performance problems appear.
What does it mean for Big O to be "asymptotic"?
It describes behavior as input grows arbitrarily large, ignoring startup costs and tiny inputs. Two algorithms can be nearly identical on 5 elements and wildly different at a million. Big O is about that long-term trend.
Can two algorithms with the same Big O complexity have very different real-world speeds?
Yes. Big O hides constant factors. An O(n) algorithm doing 1 operation per element and one doing 100 are both O(n), but the second runs about 100x slower.
What's the difference between Big O, Big Omega, and Big Theta?
Big O is an upper bound (no worse than this). Big Omega is a lower bound (no better than this). Big Theta is a tight bound, where both match. In interviews "Big O" is often used loosely for the tight bound, but formally it's an upper bound.
Insertion sort is often described as O(n²) — is that always true?
That's the worst case, such as a reverse-sorted array, where each element shifts past every sorted element. The best case is O(n): on an already sorted array, each element needs one comparison and no shifting.
Why is reading `array.length` in JavaScript O(1) instead of counting every element?
JavaScript keeps length as a property that updates automatically when elements are added or removed (push, pop, assignment, etc.). Reading it is a property access, not a recount.
Could an algorithm with worse Big O complexity actually run faster than a better one in practice? When?
Yes, for small inputs. An O(n log n) algorithm can have more overhead per operation than a simple O(n²) one, and for small n that overhead wins. That's why some real sorts switch to insertion sort for small sub-arrays inside an overall O(n log n) algorithm.