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:
[2, 5, 4, 3].[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:
[3, 2, 2, 5, 4].[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:
[2, 3, 2].[2] and 1 distinct odd number [3]. Thus, the answer is 3.
Constraints:
1 <= nums.length <= 1051 <= nums[i] <= 105Problem 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.
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.
Python
Java
C++
Go
TypeScript
| Approach | Time | Space | When to Use |
|---|---|---|---|
| Brute Force Subarray Scan | O(n²) | O(1) | Small arrays or verifying correctness during development |
| Prefix Sum + Hash Table | O(n) | O(n) | Best general solution for detecting equal prefix states |
| Segment Tree + Prefix Sum + Hash Table | O(n log n) | O(n) | Large inputs or variants requiring range queries on prefix states |
Longest Balanced Subarray II | Leetcode 3721 | Min-Max Query | Segment Tree Concept | Video 15 | MIK • codestorywithMIK • 13,794 views views
Watch 9 more video solutions →Practice Longest Balanced Subarray II with our built-in code editor and test cases.
Practice on FleetCodePractice this problem
Open in Editor