FastPrepLongest Balanced Binary Subarray
Problems/Longest Balanced Binary Subarray

Longest Balanced Binary Subarray

IBM logoIBMINTERNFULLTIMEOA

Updated Sep 2026

QuestionFunctionExamplesConstraints

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:

  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.

Function

longestBalancedBinarySubarray(arr: int[]) → int

Examples

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.

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.

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.

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 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

IBM interview experiences

  • IBM Full-Time SWE OA Questions: 1 Experience
  • IBM Software Intern Résumé Rounds: 2 Experiences (Part 3 of 3)
  • IBM Intern Blitz Interviews: 23 Experiences (Part 2 of 3)
  • IBM Software Intern Interviews: 44 Experiences (Part 1 of 3)
  • IBM Software Intern Interview Questions: 15 Experiences
All IBM interview questionsSee IBM hiring insights
Saved
class Solution {
    public int longestBalancedBinarySubarray(int[] arr) {
      // write your code here
    }
}
Checking account…