You are given an integer array arr containing only 0s and 1s.
Return the length of the longest contiguous subarray that satisfies both conditions:
- The subarray contains the same number of
0s and1s. - For every prefix of the subarray, the number of
1s is greater than or equal to the number of0s.
Examples
01 · Example 1
arr = [1, 0, 1, 1, 0, 0, 1] return = 6
The subarray [1,0,1,1,0,0] is balanced and every prefix has at least as many 1s as 0s.
02 · Example 2
arr = [0, 1, 1, 0] return = 2
The longest valid subarray is [1,0]. The full array is balanced, but its first prefix starts with more 0s than 1s.
03 · Example 3
arr = [1,0,1,1,0,0,1] return = 6
The subarray [1,0,1,1,0,0] is balanced, and every prefix has at least as many 1s as 0s.
04 · Example 4
arr = [0,1,1,0] return = 2
The full array is balanced, but its first prefix has more 0s than 1s. The longest valid subarray is [1,0].
Constraints
1 <= arr.length <= 2 * 10^5arr[i]is either0or1.
More IBM problems
- Count Descending SubarraysOA · Seen Apr 2026
- Count Power Products in RangeOA · Seen Apr 2026
- Minimum Operations to Make Alternating Binary StringSeen Feb 2026
- Minimum Number of Non-Empty Disjoint SegmentsSeen Feb 2026
- Count Unstable ProcessesOA · Seen Feb 2026
- Process Execution TimeOA · Seen Nov 2025
- Service Timeout DetectionOA · Seen Nov 2025
- Get Minimum OperationsSeen May 2025
public int longestBalancedBinarySubarray(int[] arr) {
// write your code here
}arr[1, 0, 1, 1, 0, 0, 1]
expected6
sign in to submit