← Questions

Contiguous array with equal 0s and 1s

0
MetaCodingLast asked Nov 2025

A coding interview question asked in Meta's technical phone screen, last asked Nov 2025. It tests prefix sums and hash maps.

Given an array of 0s and 1s, return the length of the longest contiguous subarray that holds as many 0s as 1s.

Interface

Unless you agree on a different interface with the interviewer, assume:

  • find_max_length(nums: list[int]) -> int — returns the length, or 0 if no such subarray exists.

Example

find_max_length([0, 1])                     ->  2
find_max_length([0, 1, 0])                  ->  2     # [0, 1] or [1, 0]
find_max_length([0, 0, 1, 0, 0, 0, 1, 1])   ->  6     # indices 2..7: three 0s, three 1s
find_max_length([1, 1, 1])                  ->  0

Constraints

  • 1 <= len(nums) <= 2 * 10^5. Each value is 0 or 1.
  • Aim for O(n) time.

Clarifying questions

  • Return the length, or the subarray's indices?
  • Can the input be empty?
  • Could the values be other than 0 and 1 (for example, two given labels)?

What a strong answer covers

  • Count 0 as -1 and 1 as +1. A subarray is balanced exactly when two prefix sums are equal.
  • A dictionary from prefix sum to the first index where it appeared, seeded with {0: -1} so a balanced prefix counts.
  • One pass, O(n) time and O(n) space. Or an array of size 2n + 1 in place of the dictionary.
  • Why you store only the first index of each sum, which gives the longest span.
  • Tests: all zeros, all ones, the whole array balanced, the answer at the very start.

Follow-ups

  • Return the start and end indices of the subarray.
  • Count the balanced subarrays instead of finding the longest.
  • Three values (0, 1, 2) that must appear equally often.

Where it's asked

  • Meta · Technical phone screen · Last asked Nov 202545 min · Two coding problems in CoderPad, about 20 minutes each · Usually no AI; some newer screens are AI-assisted

What it tests

prefix sums · hash maps

Write and test your solution herePython in your browser, the question's tests level by level, every submission kept for you.Sign in to start coding