#3719
Longest Balanced Subarray I
MediumArrayHash 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 hashmap to track the difference between counts of even and odd numbers, leveraging prefix sums to find balanced subarrays efficiently.
⚙️
Algorithm
3 steps- 1Step 1: Initialize a hashmap to store the first occurrence of each difference between even and odd counts.
- 2Step 2: Traverse the array, updating counts and calculating the difference.
- 3Step 3: If the difference has been seen before, calculate the length of the subarray and update the maximum length.
solution.py15 lines
1def longestBalanced(nums):
2 count_map = {0: -1}
3 even_count = odd_count = 0
4 max_length = 0
5 for i, num in enumerate(nums):
6 if num % 2 == 0:
7 even_count += 1
8 else:
9 odd_count += 1
10 diff = even_count - odd_count
11 if diff in count_map:
12 max_length = max(max_length, i - count_map[diff])
13 else:
14 count_map[diff] = i
15 return max_lengthℹ
Complexity note: We traverse the array once, leading to O(n) time. Space is O(n) due to the hashmap storing differences.
- 1Distinct counts of evens and odds must match.
- 2Using a hashmap allows efficient tracking of differences.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.