~/problems / Arrays & hashing / Prefix sums and difference arrays

Contiguous Array

On a phone? Coding is easier on a laptop: email this problem to yourself . Meanwhile: quiz this topic or fight a boss.

medium ~20 min

A football match log lists every goal in order: 1 means the home team scored, 0 means the away team scored. A stretch of the log is level when both teams scored the same number of goals in it.

Write find_max_length(goals: list[int]) -> int: the length of the longest level stretch of consecutive goals, or 0 if there is none.

find_max_length([1, 0, 0, 1, 1, 0, 1])               # 6: goals 0..5 are three each
find_max_length([1, 1, 0, 1, 0, 0, 0, 1, 1, 1])      # 8: goals 1..8 (or 2..9) are four each
find_max_length([1, 1, 1, 0])                        # 2: only "1, 0" at the end
find_max_length([0, 0, 0])                           # 0: the home team never scored

Constraints: 1 <= len(goals) <= 2 * 10^5, every value is 0 or 1.

⭐ Bonus: checking every stretch with a running count still passes; a speed test with 200,000 goals earns a star in O(n).

Show hint

count a home goal as +1 and an away goal as -1, and keep a running total. A stretch is level exactly when the total is the same just before it starts and at its end. For the longest stretch, remember where each total first appeared.

Topic: Prefix sums and difference arrays. O(1) range sums (1D and 2D); O(1) range updates with difference arrays.

Read the visual guide
0:00
Ctrl ' run · Ctrl ↵ submit
esc