Command Palette
Search for a command to run...
Longest Subarray with Equal 0s and 1s
Sliding Window Concepts
Longest Subarray with Equal 0s and 1s
MediumArrayStringPrefixSumHash MapSliding Window ConceptsContiguous Subarray
You are given a binary array nums consisting of only 0s and 1s.
Your task is to find the length of the longest contiguous subarray that contains an equal number of 0s and 1s.
If no such subarray exists, return 0.
This problem requires an efficient approach as brute force will not pass for large inputs.
Input Format
[nums]
Example: [0,1,0,1,1,0,0]
Output Format
Integer (length of longest valid subarray)
Constraints
1 ≤ N ≤ 200000
nums[i] ∈ {0,1}
Expected Time Complexity: O(N)
Examples
Example 1
Input:
[0,1,0,1,1,0,0]Output:
6Example 2
Input:
[0,1,1,0,1,0,0,1,1]Output:
8Example 3
Input:
[0,1]Output:
2Loading...
[0,1,0,1,1,0,0]
6