Contiguous Array
Medium · Arrays & Hashing · Array · Hash Table · Prefix Sum
Problem
You are given a binary array nums: every element is 0 or 1.
Return the length of the longest contiguous subarray that holds as many 0s as 1s. If no such subarray exists, return 0.
Examples
Input: nums = [1,1,0,1,0,0,1] Output: 6
Both [1,1,0,1,0,0] and [1,0,1,0,0,1] hold three 0s and three 1s.
Input: nums = [1,1,1] Output: 0
Without a 0 no subarray can be balanced.
Input: nums = [0,1] Output: 2
The whole array holds one 0 and one 1.
Constraints
- 1 <= len(nums) <= 10^5
- nums[i] is 0 or 1
Approaches
- Baseline: every start, extend to every end — time O(n²), space O(1)
Follow-up
What if you had to count the balanced subarrays instead of finding the longest? Keep how many times each running total has appeared instead of where it first appeared: the first use case below. With three values (0, 1, 2) and "equal counts of all three", the key becomes the pair (ones - zeros, twos - zeros).
Related problems
Start free on Cariara · Coding problems · System design studio