#3721
Longest Balanced Subarray II
HardArrayHash TableDivide and ConquerSegment TreePrefix SumHash MapArray
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n)Space O(n)
Use a hash map to track the counts of distinct even and odd numbers as we expand the subarray. Adjust the starting index when the counts are imbalanced.
⚙️
Algorithm
3 steps- 1Step 1: Initialize two hash maps to count distinct even and odd numbers.
- 2Step 2: Use two pointers to expand the end of the subarray and adjust the start when the counts are unequal.
- 3Step 3: Update the maximum length whenever the counts are equal.
solution.py21 lines
1def longestBalancedSubarray(nums):
2 left = 0
3 even_count, odd_count = {}, {}
4 max_length = 0
5 for right in range(len(nums)):
6 if nums[right] % 2 == 0:
7 even_count[nums[right]] = even_count.get(nums[right], 0) + 1
8 else:
9 odd_count[nums[right]] = odd_count.get(nums[right], 0) + 1
10 while len(even_count) != len(odd_count):
11 if nums[left] % 2 == 0:
12 even_count[nums[left]] -= 1
13 if even_count[nums[left]] == 0:
14 del even_count[nums[left]]
15 else:
16 odd_count[nums[left]] -= 1
17 if odd_count[nums[left]] == 0:
18 del odd_count[nums[left]]
19 left += 1
20 max_length = max(max_length, right - left + 1)
21 return max_lengthℹ
Complexity note: The algorithm efficiently counts distinct numbers using hash maps, leading to linear time complexity.
- 1Using hash maps allows efficient counting of distinct elements.
- 2Two-pointer technique helps maintain balance dynamically.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.