Data Structures & AlgorithmsHardProduct Company SDE · prefix-sum OA

Problem: The longest subarray with equally many 0s and 1s of a = [0, 1, 0, 0, 1, 1, 0] is needed. Run the prefix-balance code and print the length.

Problem: The longest subarray with equally many 0s and 1s of a = [0, 1, 0, 0, 1, 1, 0] is needed. Run the prefix-balance code and print the length.
a = [0, 1, 0, 0, 1, 1, 0]
first = {0: -1}
s = 0
best = 0
for i, x in enumerate(a):
    s += 1 if x else -1
    if s in first:
        best = max(best, i - first[s])
    else:
        first[s] = i
print(best)
What is printed?
  1. A. 6
  2. B. 4
  3. C. 2
  4. D. 7

Correct answer: A. 6

The subarray a[0..5] = [0,1,0,0,1,1] has three 0s and three 1s. Storing only the first occurrence of each balance gives the longest span between equal balances.

More Coding Interview Problems questions

Exams that ask this topic