Problem

Longest Balanced Binary Subarray

IBMINTERNFULLTIMEOA
See IBM hiring insights

You are given an integer array arr containing only 0s and 1s.

Return the length of the longest contiguous subarray that satisfies both conditions:

  1. The subarray contains the same number of 0s and 1s.
  2. For every prefix of the subarray, the number of 1s is greater than or equal to the number of 0s.
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^5
  • arr[i] is either 0 or 1.
More IBM problems
drafts saved locally
public int longestBalancedBinarySubarray(int[] arr) {
  // write your code here
}
arr[1, 0, 1, 1, 0, 0, 1]
expected6
sign in to submit