Lesson 3.4
Spot repeated work
7 min · 7 steps
Step 1 of 7 · Explanation
Problem: "Return an array where
out[i]is the sum ofnums[0]throughnums[i]."The brute force adds everything up again from the start for each
i, with an innerjloop from 0 toi. For[3, 1, 4, 2],out[2]computes 3 + 1 + 4 from zero, even though 3 + 1 was already worked out forout[1]. Each round redoes the additions the previous round already did.Step 2 of 7 · Predict the result
How many additions happen for 4 items?
function solution(nums) { let adds = 0 for (let i = 0; i < nums.length; i++) { for (let j = 0; j <= i; j++) { adds++ } } return adds}10416
Step 3 of 7 · Pick the approach
A brute force running sum: the outer loop
ivisits every item. Inside it,sumstarts at 0, ajloop addsnums[0]throughnums[i], thenout.push(sum).
What work keeps getting repeated?- Adding up
nums[0]throughnums[i - 1]again, when the previous round already had that sum out.push(sum)on every round- The outer loop
i - Reading
nums.length
- Adding up
Step 4 of 7 · Arrange the code
Build the O(n) running sum, where
out[i]is the sum ofnums[0]throughnums[i]. Keep the sum so far. Two lines don't belong.return outsum += nums[i]out.push(sum)}const out = []}for (let i = 0; i < nums.length; i++) {let sum = 0function solution(nums) {sum = nums[i]for (let i = 1; i < nums.length; i++) {Step 5 of 7 · Pick the approach
Another brute force: "For each
i, use an inner loop to check whethernums[i]appeared earlier." That's O(n²).
What can answer "seen it before?" in one step?- A Set or Map that stores every number you've passed
- Re-sort the array on every round
- An inner loop with
j = i + 1 - One variable holding the previous number
Step 6 of 7 · Predict the result
What does it return for
[5, 3, 5, 3]?function solution(nums) { const seen = new Map() for (let i = 0; i < nums.length; i++) { if (seen.has(nums[i])) { return [seen.get(nums[i]), i] } seen.set(nums[i], i) } return []}[0, 2][1, 3][2, 0][]
Step 7 of 7 · Recap
- Once the brute force works, look for an inner loop that recomputes something.
- Keep the result so far, like a running total, so it's never recounted.
- "Seen it before?" can be answered in one step with a Set or Map.