Longest Balanced Binary Subarray
Updated
Problem statement
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.
Function
longestBalancedBinarySubarray(arr: int[]) → intExamples
Example 1
arr = [1, 0, 1, 1, 0, 0, 1]return = 6The subarray [1,0,1,1,0,0] is balanced and every prefix has at least as many 1s as 0s.
Example 2
arr = [0, 1, 1, 0]return = 2The longest valid subarray is [1,0]. The full array is balanced, but its first prefix starts with more 0s than 1s.
Example 3
arr = [1,0,1,1,0,0,1]return = 6The subarray [1,0,1,1,0,0] is balanced, and every prefix has at least as many 1s as 0s.
Example 4
arr = [0,1,1,0]return = 2The 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 Online Assessment questions
- Missing IntervalsOA · Seen Nov 2026
- Count Peaks and ValleysOA · Seen Nov 2026
- Last Object Exit TimeOA · Seen Nov 2026
- Count Strictly Increasing Contiguous WindowsOA · Seen Nov 2026
- Total Each Letter's Count in an Encoded StringOA · Seen Nov 2026
- Count Servers With No Requests in a Time WindowOA · Seen Nov 2026
- Maximum Easy Tasks After RearrangingOA · Seen Nov 2026
- Tree Pythagorean TriplesOA · Seen Oct 2026
- Minimum Power-of-Two Removal OperationsOA · Seen Oct 2026
- Maximum Compatible Time WindowsOA · Seen Oct 2026