DSA Factory
Free Arrays lessonsArrays · Stage 7 · Prefix sums · Step 3

Same total twice

Spot a stretch that sums to zero by remembering every running total. About 9 minutes.

Back where you started

You go on a hike with a step counter that shows height gained and lost. At some point the display reads exactly what it read an hour ago. Whatever you climbed and descended in that hour cancelled out: it added up to 0.

Running totals work the same way. If the total after some box equals a total you had earlier, the numbers in between sum to zero.

Same total again: the stretch in between sums to 0.
Running totals: 4, 6, 3, 4
4
0
2
1
-3
2
1
3
6
4
i

total 4. Seen {0}? No. Add 4.

Move 1 of 4

Remember every total in a set

Walk the array, keeping a running total, and store every total you reach in a set. Each new total asks one question: have I been here before?

Put 0 in the set before you start, standing for "before the first box". Otherwise a stretch that starts right at the beginning, like 3 then −3, would be missed.

Start with 0 in the set: for stretches that start at the beginning.
In code
seen = {0}
total = 0
for x in nums:
    total += x
    if total in seen:
        return True
    seen.add(total)
return False
Quick check

The numbers are 3, −3, 5, and the set starts with just 0. When is a repeat found?

  1. AAfter the −3 (the total is 0 again)
  2. BNever
  3. CAfter the 5
Show the answer

After the −3 (the total is 0 again). 0 is already in the set, so 3 + (−3) = 0 is found.

Your problem

Zero-sum stretch

You get a list of numbers. Return true if some non-empty run of consecutive numbers adds up to exactly 0. Otherwise return false.

Example
nums = [4, 2, -3, 1, 6] → true

0 ≤ n ≤ 1,000,000 · −10^6 ≤ each value ≤ 10^6

Solve it in your browserFree account, no card. Python, C++, Java or JavaScript, with hints if you get stuck, and your progress is saved.
Sign up free to solve