75. Zeros Meet Ones

A sensor logs one bit per second into the array nums: a 1 means a signal was detected and a 0 means silence. An engineer wants the longest balanced window, meaning a stretch of consecutive seconds in which the number of detected signals equals the number of silent seconds.

Return the length of the longest contiguous subarray of nums that contains the same number of 0s and 1s. If no such subarray exists, return 0. Every element of nums is either 0 or 1, and a balanced window always has an even length.

Example 1

Input:
nums = [1,1,0,1,0,0,1]
Output:
6
Explanation:

The subarray [1,0,1,0,0,1] from index 1 to index 6 has three 1s and three 0s, and nothing longer is balanced.

Example 2

Input:
nums = [1,1,1]
Output:
0
Explanation:

There are no zeros, so no balanced window exists.

Constraints

1 ≤ nums.length ≤ 106

nums[i] is 0 or 1

How this problem is judged

Answers
Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.
Time per case
Python 2,000 msC++ 500 msJava 1,000 msJavaScript 1,000 msTypeScript 1,000 ms

Expected complexity

Time
O(n)
Space
O(n)

What the author was aiming for. Your own solution is not measured against it.

Asked in an interview

Were you asked this in an interview? Say where, anonymously.

Code
Loading the editor…