Problem 334423 · medium · Phase 03 Linear Management & Searching

Longest Even Shift

prefix sums · hash map · first occurrence

A machine log records one entry per minute: 1 when the machine was running and 0 when it was idle. A shift is even when it contains the same number of running and idle minutes. Return the length of the longest contiguous even shift, or 0 if none exists.

Examples

Input:  log = [0, 1, 1, 0, 1, 1, 1, 0]
Output: 4
Explanation: minutes 0..3 hold two 0s and two 1s; no longer stretch is balanced.

Input:  log = [1, 1, 1]
Output: 0

Input:  log = [1, 0]
Output: 2

Constraints

  • 0 <= len(log) <= 10**5, each entry is 0 or 1
  • Target complexity: O(n) time. Checking every stretch is too slow.

Goals

  • Map a 0/1 balance condition onto equal prefix values
  • Store the first index of each prefix value to maximise length
Starting Python…