AlgoInsight

DSA problem

Longest Balanced Subarray II

HardBinary Indexed Tree / Segment TreePattern: Binary Indexed Tree / Segment Treetop600GoogleAmazonMicrosoftMeta

Given a binary array nums of length n and a list of queries queries[i] = [L_i, R_i], for each query return the length of the longest contiguous subarray of nums[L_i..R_i] containing an equal number of 0s and 1s.

The classic prefix-balance trick reduces "equal zeros and ones" to "two indices with the same prefix value". Define balance[i] as (count of 1s minus count of 0s) in nums[0..i-1], so balance[0] = 0 and balance[i+1] = balance[i] +/- 1. A subarray (i, j] is balanced iff balance[j] == balance[i]. Therefore the global answer over a fixed range [L, R] is the maximum of (j - i) over all pairs (i, j) with L <= i < j <= R + 1 and balance[i] == balance[j].

For a single query this is solvable in O(R - L + 1) with a hash map that remembers, for each balance value, the leftmost index seen inside the current window. To answer many queries efficiently we go offline: sort queries by R and sweep j from 0 to n. For each balance value b we maintain its most recent occurrence inside the sweep. As j grows we update a segment tree indexed by i (the position of that "earlier" occurrence) holding the value j - i. Each query [L, R] becomes a max-range query on the segment tree restricted to indices i >= L and j <= R + 1.

Because balance can range from -n to +n, shift everything by +n so the values become non-negative array indices into a "last seen position by balance" array. The total time is O((n + Q) log n) with O(n) memory.

Examples

Example 1
Input: nums = [0,1,0,0,1,1,0], queries = [[0,6],[2,5],[0,3]]
Output: [6,4,2]
Explanation: For [0,6] the whole array of length 7 has 4 zeros and 3 ones — not balanced. The longest balanced sub-window is nums[0..5] = [0,1,0,0,1,1] with three 0s and three 1s, length 6. For [2,5] nums[2..5] = [0,0,1,1] has length 4 and is balanced. For [0,3] the longest balanced prefix is nums[0..1] = [0,1] of length 2.
Example 2
Input: nums = [1,1,1,0], queries = [[0,3],[0,2]]
Output: [2,0]
Explanation: For [0,3] only nums[2..3] = [1,0] has balance, length 2. For [0,2] = [1,1,1] no balanced subarray exists, so 0.
Example 3
Input: nums = [0,1], queries = [[0,1]]
Output: [2]
Explanation: The single subarray [0,1] already has one 0 and one 1.

Constraints

4 hints and a full solution walkthrough with step-by-step visualizations are available in the practice editor.

segment-treeprefix-sumoffline-queriesarrayhash-table

Browse all DSA problems