Skip to content

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.

19 min read0/7 questions

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 forceStructure that removes itCost per step: before → after
Searching earlier elements for a valueHash map or setO(n) → O(1)
Finding the min / max of a changing collectionHeapO(n) → O(log n)
Summing a range again and againPrefix sumsO(n) → O(1)
Solving the same subproblem in recursionMemo table (DP)exponential → once per state
Scanning back for the next greater / smallerMonotonic stackO(n) → amortised O(1)
Linear search in sorted dataBinary searchO(n) → O(log n)
Re-adding a whole window after one slideRunning window totalO(k) → O(1)
Checking whether two items are connected, many timesUnion-findO(n) → nearly O(1)
Re-sorting the collection after every changeSort once, a heap, or bisect.insortO(n log n) → O(log n) or O(n)
Taking the max of each sliding window from scratchMonotonic dequeO(k) → amortised O(1)
Quick check
Brute force for Contains Duplicate: for each i, loop over every j < i and check nums[j] == nums[i]. What is the inner loop really doing?
Need a nudge? A hint rules out a wrong answer.

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.

Prefix sums turn a range sum into one subtraction
3
0
1
1
4
2
1
3
5
4

The array. We will be asked for many range sums.

1/4
Python
nums = [3, 1, 4, 1, 5] prefix = [0]for x in nums: prefix.append(prefix[-1] + x) def range_sum(l, r): return prefix[r + 1] - prefix[l] print(prefix)print(range_sum(1, 3), sum(nums[1:4]))print(range_sum(0, 4), sum(nums))
Output
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.

Predict the outputPython

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])
Need a nudge? Hints walk you through it.

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.

Python
calls = 0 def ways(n): global calls calls += 1 if n <= 1: return 1 return ways(n - 1) + ways(n - 2) print(ways(20), "calls:", calls) memo = {}calls = 0 def ways_memo(n): global calls calls += 1 if n <= 1: return 1 if n not in memo: memo[n] = ways_memo(n - 1) + ways_memo(n - 2) return memo[n] print(ways_memo(20), "calls:", calls)
Output
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 pairs0/5 matched

Match the repeated work to the structure that removes it.

Choose an item, then its match on the other side.

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.

Monotonic deque for window max, k = 3
1
0
↑i
3
1
-1
2
-3
3
5
4
deque = [0]

Push index 0 (value 1). Nothing to compare yet.

1/5
Python
import randomfrom collections import deque def brute(nums, k): return [max(nums[i:i + k]) for i in range(len(nums) - k + 1)] def window_max(nums, k): dq = deque() # indices; their values are decreasing out = [] for i, x in enumerate(nums): while dq and nums[dq[-1]] <= x: dq.pop() # x beats them, they can never be a max again dq.append(i) if dq[0] <= i - k: dq.popleft() # front slid out of the window if i >= k - 1: out.append(nums[dq[0]]) return out print(window_max([1, 3, -1, -3, 5, 3, 6, 7], 3))for _ in range(1000): k = random.randint(1, 5) nums = [random.randint(-5, 5) for _ in range(random.randint(k, 10))] assert brute(nums, k) == window_max(nums, k), (nums, k)print("1000 random tests agree")
Output
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.

Predict the outputPython

What does window_max([4, 2, 12, 3], 2) return?

print(window_max([4, 2, 12, 3], 2))
Need a nudge? Hints walk you through it.

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.insort in 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 with sys.stdin.read().split() and walk the tokens. In Node, read the whole of stdin in one go rather than using a per-line readline loop when the input is large.
  • Printing in a loop. Each print call has overhead. Collect results in a list and print "\n".join(map(str, out)) once.
  • Hidden quadratic work. x in some_list inside a loop, list.pop(0), string += in a tight loop, and JS array.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.

Quick check
Your O(n) Python solution times out on an OA with n = 10^6 lines of input. It calls input() once per line and print() once per result. What do you try first?
Need a nudge? A hint rules out a wrong answer.

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 it in order5 steps

Put the optimisation routine in order.

  1. Tap the steps below in the right order.
Need a nudge? A hint shows where it starts.
Quick check
A simulation repeatedly scans a list of n tasks to find the one with the earliest deadline, removes it, and adds new tasks. What removes the bottleneck?
Need a nudge? A hint rules out a wrong answer.

Practice

Find the repeated work in the brute force, then remove it with a running product from each side.

ChallengeMedium

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.
def product_except_self(nums: list[int]) -> list[int]: # Everything to the left times everything to the right. pass
Key terms
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.