Arrays and Hashing Prefix sums
78. Contiguous Array
You are given an array nums in which every element is either 0 or 1. Return the length of the longest
subarray that holds as many 0s as 1s. If no such subarray exists, return 0.
A subarray is a contiguous sequence of elements from nums.
Example 1
Input: nums = [0, 1, 1, 1, 0, 0, 1, 1]
6Explanation: The first six elements, [0, 1, 1, 1, 0, 0], hold three 0s and three 1s. A balanced subarray always has
an even length, and the only longer one to try is the whole array, which holds five 1s and three 0s.
Example 2
Input: nums = [1, 0]
2Explanation: The whole array holds one 0 and one 1, so the answer is its full length.
Example 3
Input: nums = [0, 1, 1, 1, 0]
2Explanation: [0, 1] at the start and [1, 0] at the end are both balanced. Any longer stretch that holds both 0s
also holds all three 1s, so the two 0s never fit in one balanced subarray.
Check your understanding
Work out the answer for this input before you write any code.
Constraints
1 ≤ nums.length ≤ 105nums[i]is either0or1
Clarifying questions
What you would ask an interviewer before writing any code.