Skip to main content

Longest Balanced Subarray II - Solution & Explanation

HardArrayHash TableDivide and ConquerSegment Tree16 min readAsked at: Amazon, Google
Practice this problem

Problem Statement

You are given an integer array nums.

A subarray is called balanced if the number of distinct even numbers in the subarray is equal to the number of distinct odd numbers.

Return the length of the longest balanced subarray.

 

Example 1:

Input: nums = [2,5,4,3]

Output: 4

Explanation:

  • The longest balanced subarray is [2, 5, 4, 3].
  • It has 2 distinct even numbers [2, 4] and 2 distinct odd numbers [5, 3]. Thus, the answer is 4.

Example 2:

Input: nums = [3,2,2,5,4]

Output: 5

Explanation:

  • The longest balanced subarray is [3, 2, 2, 5, 4].
  • It has 2 distinct even numbers [2, 4] and 2 distinct odd numbers [3, 5]. Thus, the answer is 5.

Example 3:

Input: nums = [1,2,3,2]

Output: 3

Explanation:

  • The longest balanced subarray is [2, 3, 2].
  • It has 1 distinct even number [2] and 1 distinct odd number [3]. Thus, the answer is 3.

 

Constraints:

  • 1 <= nums.length <= 105
  • 1 <= nums[i] <= 105

Approach Overview

Problem Overview: You receive an array and must find the length of the longest subarray that satisfies a specific balance condition between its elements. The challenge is detecting equalized prefix states efficiently across the array while handling large input sizes where brute force checks are too slow.

Approach 1: Brute Force Subarray Check (O(n²) time, O(1) space)

Enumerate every possible subarray using two nested loops. For each start index i, extend the end index j and recompute the balance condition by counting values inside the window. This guarantees correctness but quickly becomes impractical as n grows because every candidate segment requires recomputation. This approach is useful for understanding the structure of balanced segments but fails typical interview constraints.

Approach 2: Prefix Sum + Hash Table (O(n) time, O(n) space)

Convert the balance requirement into a prefix-state equality problem. Maintain a running prefix sum or balance score that represents the difference between categories of elements. If two indices share the same prefix state, the subarray between them is balanced. Store the first occurrence of each prefix state in a hash table. As you iterate through the array, compute the current prefix state and check whether it has appeared before. The distance between the first occurrence and the current index forms a balanced subarray candidate.

Approach 3: Segment Tree + Prefix Sum + Hash Table (O(n log n) time, O(n) space)

For larger constraints or extended balance definitions, combine prefix sums with a segment tree. First compute prefix balance values for every index. A hash table tracks earliest occurrences of prefix states, while the segment tree supports efficient range queries when evaluating candidate spans during divide-and-conquer processing. The tree allows fast retrieval of valid prefix boundaries and ensures each segment is processed in logarithmic time. This hybrid structure handles cases where prefix states must be validated across multiple ranges rather than a single linear scan.

Recommended for interviews: Interviewers typically expect the prefix sum + hash map insight because it converts the problem from subarray enumeration to prefix-state matching. Demonstrating the brute force approach first shows you understand the definition of a balanced segment. The optimized solution proves you recognize the core pattern used in many longest subarray with equal counts problems.

Solution

We can transform the problem into a prefix sum problem. Define a prefix sum variable now, representing the difference between odd and even numbers in the current subarray:

$ now = distinct odd numbers - distinct even numbers

For odd elements, record as +1, and for even elements, record as -1. Use a hash table last to record the last occurrence position of each number. If a number appears repeatedly, we need to revoke its previous contribution.

To efficiently calculate the subarray length each time a right endpoint element is added, we use a segment tree to maintain the minimum and maximum values of the interval prefix sum, while supporting interval addition operations and binary search queries on the segment tree. When iterating to right endpoint i, first update the contribution of the current element, then use the segment tree to query the earliest position pos where the current prefix sum now appears. The current subarray length is i - pos, and we update the answer:

ans = max(ans, i - pos)

The time complexity is O(n log n), where n is the length of the array. Each segment tree modification and query operation takes O(log n), and enumerating the right endpoint n times gives a total time complexity of O(n log n). The space complexity is O(n), where segment tree nodes and the hash table each occupy O(n)$ space.

Code

Python

Java

C++

Go

TypeScript

Try this approach in the editor →

Detailed Complexity Analysis

ApproachTimeSpaceWhen to Use
Brute Force Subarray ScanO(n²)O(1)Small arrays or verifying correctness during development
Prefix Sum + Hash TableO(n)O(n)Best general solution for detecting equal prefix states
Segment Tree + Prefix Sum + Hash TableO(n log n)O(n)Large inputs or variants requiring range queries on prefix states

Video Solution

Longest Balanced Subarray II | Leetcode 3721 | Min-Max Query | Segment Tree Concept | Video 15 | MIK • codestorywithMIK • 16,036 views views

Watch 9 more video solutions →

Frequently Asked Questions

Is Longest Balanced Subarray II easy or hard?
Longest Balanced Subarray II is typically classified as a hard problem because the balance condition must be converted into a prefix-state equality problem. Recognizing that repeated prefix states imply a balanced segment is the key insight, and implementing the optimized structure efficiently requires strong understanding of arrays and hashing.
Longest Balanced Subarray II Python/Java solution
Most implementations compute a running prefix balance while iterating through the array and store the earliest index for each balance value in a hash map. The same logic translates directly across Python, Java, C++, Go, and TypeScript because it relies on standard dictionary or map operations.
How to solve Longest Balanced Subarray II in O(n)?
Transform the balance requirement into a prefix state. Iterate through the array while maintaining a running prefix value. Store the first index of each prefix state in a hash map. Whenever the same state appears again, compute the length between indices and update the maximum balanced subarray length.
What is the best approach for Longest Balanced Subarray II?
The most practical approach uses prefix sums combined with a hash table to track previously seen balance states. Each prefix state represents the difference between element categories. When the same state appears again, the subarray between the two indices is balanced. For more advanced variants, a segment tree can help process prefix ranges efficiently.
Is Longest Balanced Subarray II asked at Google/Amazon/Meta?
Variants of longest balanced or equal-count subarray problems appear frequently in interviews at companies like Amazon, Google, and Meta. They test understanding of prefix sums, hash maps, and array scanning techniques rather than brute force enumeration.
What data structure is used in Longest Balanced Subarray II?
The main structures are prefix sums, hash tables for storing first occurrences of balance states, and sometimes a segment tree for efficient range queries. Together they allow fast detection of matching prefix configurations that form balanced subarrays.
What is the time complexity of Longest Balanced Subarray II?
The optimized implementation runs in O(n log n) time when using a segment tree with prefix sums and a hash table. The segment tree supports logarithmic range queries while scanning the array. Simpler prefix-hash implementations can reach O(n) time if the balance condition can be represented by a single prefix state comparison.

Ready to solve this problem?

Practice Longest Balanced Subarray II with our built-in code editor and test cases.

Practice on FleetCode