DSAPrefix + HashLongest

Longest Zero-Sum Subarray Visualizer

What is the Longest Zero-Sum Subarray

A subarray sums to 0 when two prefixes are equal — everything between them cancelled. To get the longest such span, store the first index of each prefix. When the prefix repeats at i, a candidate length is i − first[pref]. Seed 0 → −1 so a zero-sum prefix from the start is counted.

  • Equal prefixes ⇒ zero middle.
  • Keep the earliest index so later repeats only grow the window.
  • Negatives are required — a shrinking window would be wrong.

How this visualizer works

Array 15, -2, 2, -8, 1, 7, 10, 23. Prefix 15 repeats after -2 2 -8 1 7, length 5.

Interactive trace

hash_table.state

Input
Hash table
Current look-up
Match / window
Stored entry

current_action

Load an input, then press Play or Step.

live_trace.py

1def longestZeroSum(arr):
2first, pref, best = {0: -1}, 0, 0
3for i, x in enumerate(arr):
4pref += x
5if pref in first:
6best = max(best, i - first[pref])
7else:
8first[pref] = i
9return best

stdout — decision log

// each hash probe is recorded here
Speed Ready

Pseudocode & Complexity

idea.txt

1def longestZeroSum(arr):
2first, pref, best = {0: -1}, 0, 0
3for i, x in enumerate(arr):
4pref += x
5if pref in first:
6best = max(best, i - first[pref])
7else:
8first[pref] = i
9return best

complexity.md

OperationTime
Each prefixO(1) expected
Full scanO(n)
SpaceO(n)

Python implementation

solution.py

1def longestZeroSum(arr):
2 first, pref, best = {0: -1}, 0, 0
3 for i, x in enumerate(arr):
4 pref += x
5 if pref in first:
6 best = max(best, i - first[pref])
7 else:
8 first[pref] = i
9 return best