← All coding problems
Longest Subarray With Equal 0s and 1s
mediumArrays & Prefix Sums+20 XPTime limit 2s
The array contains only 0s and 1s. Find the length of the longest contiguous subarray that has as many 0s as 1s.
Input:
- line 1:
n - line 2:
nvalues, each0or1
Output: the length of the longest balanced subarray, or 0 if there is none.
Constraints: 1 ≤ n ≤ 10⁵.
Think about it: count every 0 as −1 and every 1 as +1. Now you need the longest subarray with sum 0: two equal prefix sums mark its ends. Remember the first index of each prefix sum.
Sample input 1
7 0 1 1 0 1 1 1
Sample output 1
4
Sample input 2
2 1 1
Sample output 2
0
Read input from standard input and print the answer to standard output. Your code runs in a secure sandbox against the samples (Run) and hidden tests (Submit).