Lesson 8 of 27From idea to plan
Find the Bottleneck
Spot the repeated work inside a brute force and pick the data structure that removes it.
Most optimal solutions are not new ideas. They are the brute force with one piece of repeated work taken out. The brute force for Two Sum searches the array again for every number; the optimal one remembers what it has seen. Learning to point at the line that repeats work, and to name the structure that removes it, is the most reliable way to get from O(n²) to O(n).
Where is the time going?
Take your brute force and ask, line by line: which line runs the most times, and is it doing work that was already done? That line is the bottleneck. In a nested loop it is almost always the inner loop.
Then ask a sharper question: what is the inner loop really looking for? The answer names the fix.
- The inner loop searches for a value → remember values in a hash map or set.
- The inner loop finds the minimum or maximum of what is left → keep a heap.
- The inner loop adds up a range → precompute prefix sums.
- A recursive call recomputes the same subproblem → memoise it.
- The inner loop looks back for the previous bigger value → keep a monotonic stack.
- The inner loop checks every value up to x in a sorted list → binary search.
The bottleneck table
| Repeated work in the brute force | Structure that removes it | Cost per step: before → after |
|---|---|---|
| Searching earlier elements for a value | Hash map or set | O(n) → O(1) |
| Finding the min / max of a changing collection | Heap | O(n) → O(log n) |
| Summing a range again and again | Prefix sums | O(n) → O(1) |
| Solving the same subproblem in recursion | Memo table (DP) | exponential → once per state |
| Scanning back for the next greater / smaller | Monotonic stack | O(n) → amortised O(1) |
| Linear search in sorted data | Binary search | O(n) → O(log n) |
| Re-adding a whole window after one slide | Running window total | O(k) → O(1) |
| Checking whether two items are connected, many times | Union-find | O(n) → nearly O(1) |
| Re-sorting the collection after every change | Sort once, a heap, or bisect.insort | O(n log n) → O(log n) or O(n) |
| Taking the max of each sliding window from scratch | Monotonic deque | O(k) → amortised O(1) |
i, loop over every j < i and check nums[j] == nums[i]. What is the inner loop really doing?Removing a repeated range sum
Here is a classic case. You get many questions "what is the sum of nums[l..r]?". The brute force adds up the range every time, O(n) per question. But every range sum is a difference of two prefix sums: totals from the start up to a point.
The array. We will be asked for many range sums.
Press Run (⌘ Enter) to see what happens.O(n) once to build, then O(1) per question. With 10^5 questions on 10^5 numbers, that is 2 · 10^5 steps instead of up to 10^10.
With prefix = [0, 2, 7, 8, 12], what is the sum of indices 1 to 2 of the original array?
prefix = [0, 2, 7, 8, 12] l, r = 1, 2 print(prefix[r + 1] - prefix[l])
Repeated subproblems
Recursion has its own kind of waste. The naive Fibonacci (and Climbing Stairs, which is the same recurrence) calls f(n − 1) and f(n − 2), and each of those calls the same smaller values again. f(3) gets computed many times over.
Press Run (⌘ Enter) to see what happens.The answer is the same; the call count drops from about 22,000 to 39. The bottleneck was "solving the same subproblem again", and the fix was a memo table. That is the core of dynamic programming.
Match the repeated work to the structure that removes it.
A worked example: Sliding Window Maximum
"Given nums and k, return the maximum of every window of size k. n up to 10^5, k up to n." The brute force takes max(nums[i:i + k]) for each start, which is O(n · k). With both at 10^5 that is up to 10^10, far too slow.
What is the repeated work? When the window slides one step, only one number leaves and one arrives, yet the brute force re-reads all k. A running total fixes this for sums because subtraction undoes addition. Max has no "undo", so a single running value is not enough.
The insight is about which numbers can ever matter. If a newer number is at least as big as an older one, the older one can never be the max again: the newer one is in every future window the older one is in, and it is bigger. So keep a deque of indices whose values are decreasing. Pop smaller values off the back when a new number arrives, pop the front when it slides out of the window, and the front is always the current max.
Push index 0 (value 1). Nothing to compare yet.
Press Run (⌘ Enter) to see what happens.A heap also works here, in O(n log k): push (-value, index) and lazily pop entries whose index has left the window. Mention it as the first improvement if the deque does not come to you. It is a correct, explainable step up from O(n · k), and the interviewer may nudge you to the deque from there.
What does window_max([4, 2, 12, 3], 2) return?
print(window_max([4, 2, 12, 3], 2))
Repeated sorting
A quieter bottleneck is calling sort() inside a loop. "After each insert, report the median" written as append then sort costs O(n log n) per step and O(n² log n) overall. Ask what the sort is for:
- You only need the smallest or largest each time: a heap, O(log n) per step.
- You need the collection kept in order for lookups:
bisect.insortin Python, which finds the spot in O(log n) but shifts items in O(n). Fine for n around 10^4, not 10^6. - You need the median: two heaps, one for each half. That is the classic Find Median from Data Stream answer.
- The data does not change between queries: sort once before the loop.
Neither Python nor JavaScript ships a balanced search tree, which is why heaps and bisect carry so much weight in interviews. Choosing Data Structures covers what to do when you truly need an ordered set.
When the bottleneck is not the algorithm
In an online assessment you can have the right Big O and still hit Time Limit Exceeded. Before you rethink the algorithm, check the boring parts.
- Reading input line by line. In Python, calling
input()10^5 times is slow. Read everything at once withsys.stdin.read().split()and walk the tokens. In Node, read the whole of stdin in one go rather than using a per-linereadlineloop when the input is large. - Printing in a loop. Each
printcall has overhead. Collect results in a list and print"\n".join(map(str, out))once. - Hidden quadratic work.
x in some_listinside a loop,list.pop(0), string+=in a tight loop, and JSarray.shift()all look O(1) and are not. - Recursion depth. A deep DFS in Python can crash at the default limit of 1000 frames long before it is slow. Convert to an explicit stack.
A useful check: if your solution is O(n log n) with n = 2 · 10^5 and still times out, the bottleneck is almost certainly I/O or a hidden linear call, not the algorithm. Online Assessments covers stdin templates, and Your Language's Interview Toolkit lists the hidden costs per language.
input() once per line and print() once per result. What do you try first?A worked example: Product of Array Except Self
Brute force: for each i, multiply every other number. O(n²). What is repeated? The product of everything left of i is the product left of i − 1, times one more number. Same for the right side. So the repeated work is a running product, which is prefix sums with multiplication instead of addition.
Put the optimisation routine in order.
- Tap the steps below in the right order.
Practice
Find the repeated work in the brute force, then remove it with a running product from each side.
Product of Array Except Self
Given a list of integers nums, return a list answer where answer[i] is the product of every number except nums[i]. Do it in O(n) time without using division.
nums = [1, 2, 3, 4] → [24, 12, 8, 6]
nums = [2, 3] → [3, 2]
nums = [1, 2, 0, 4] → [0, 0, 8, 0]Constraints
2 <= nums.length <= 10^5-30 <= nums[i] <= 30- Every prefix and suffix product fits in a 32-bit integer.
- bottleneck
- The line that runs most often and repeats work. Usually the inner loop of a brute force.
- prefix sums
- Running totals from the start. Any range sum becomes
prefix[r + 1] − prefix[l]in O(1). - memoisation
- Storing the result of each subproblem so recursion computes it only once.
- time–space trade
- Using extra memory (a map, a table) to avoid repeating work. O(n) space for O(n) time is common.
- monotonic deque
- A double-ended queue kept in increasing or decreasing order, so the front is always the current window's min or max.
- amortised O(1)
- Some steps cost more, but the total over n steps is O(n), like pushing and popping a monotonic stack.