Data Structures & AlgorithmsHardProduct Company SDE · Amazon/Microsoft-style OA

Problem: Find the length of the longest subarray with equal numbers of 0s and 1s.

Problem: Find the length of the longest subarray with equal numbers of 0s and 1s.
def longest_eq(a):
    first = {0: -1}; bal = best = 0
    for i, x in enumerate(a):
        bal += 1 if x else -1
        if bal in first: best = max(best, i - first[bal])
        else: first[bal] = i
    return best
print(longest_eq([0, 1, 1, 0, 1, 1, 1, 0]), longest_eq([1, 1, 1]))
What is printed?
  1. A. 4 0
  2. B. 6 0
  3. C. 4 3
  4. D. 8 0

Correct answer: A. 4 0

Treat 0 as −1 and 1 as +1; equal counts mean equal running balance at both ends. Store the FIRST index of each balance (with balance 0 at index −1) to maximise length. [0, 1, 1, 0] gives 4; no longer stretch balances. All 1s never repeat a balance → 0. Overwriting with the latest index would shrink answers. O(n).

More Coding Interview Problems questions

Exams that ask this topic