Longest Balanced Subarray I Problem
#3719
Try it yourself first
Five languages, sample and hidden tests, right in the browser.
Practice it as an interview
Talk through your solution with an AI interviewer while you code.
Description
LeetCode Problem 3719.
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 <= 15001 <= nums[i] <= 10^5
Solution
Approach: Hash Set + Enumeration
Fix the left end i and extend the right end j. Keep a set vis of the values already seen in nums[i..j] and a pair cnt with the number of distinct even and distinct odd values. A new value increments the counter of its parity. Whenever cnt[0] == cnt[1], the subarray is balanced, so update the answer with j - i + 1.
Complexity: O(n^2) time and O(n) space.
class Solution:
def longestBalanced(self, nums: List[int]) -> int:
n = len(nums)
ans = 0
for i in range(n):
cnt = [0, 0]
vis = set()
for j in range(i, n):
if nums[j] not in vis:
cnt[nums[j] & 1] += 1
vis.add(nums[j])
if cnt[0] == cnt[1]:
ans = max(ans, j - i + 1)
return ans