Longest Balanced Subarray I

medium array hash table distinct count

Problem

Given an integer array nums, a subarray is balanced when its number of distinct even values equals its number of distinct odd values. Return the length of the longest balanced subarray.

Inputnums = [2, 5, 4, 3]
Output4
The whole array is balanced: distinct evens {2, 4} and distinct odds {5, 3} both have size 2, so the length is 4.

def longestBalanced(nums):
    n = len(nums)
    best = 0
    for i in range(n):                  # fix the left end
        even, odd = set(), set()        # distinct values seen
        for j in range(i, n):           # extend the right end
            if nums[j] % 2 == 0:
                even.add(nums[j])
            else:
                odd.add(nums[j])
            if len(even) == len(odd):   # balanced window
                best = max(best, j - i + 1)
    return best
function longestBalanced(nums) {
  const n = nums.length;
  let best = 0;
  for (let i = 0; i < n; i++) {        // fix the left end
    const even = new Set(), odd = new Set();
    for (let j = i; j < n; j++) {      // extend the right end
      if (nums[j] % 2 === 0) even.add(nums[j]);
      else odd.add(nums[j]);
      if (even.size === odd.size)       // balanced window
        best = Math.max(best, j - i + 1);
    }
  }
  return best;
}
int longestBalanced(int[] nums) {
    int n = nums.length, best = 0;
    for (int i = 0; i < n; i++) {                 // fix the left end
        Set<Integer> even = new HashSet<>();
        Set<Integer> odd = new HashSet<>();
        for (int j = i; j < n; j++) {             // extend the right end
            if (nums[j] % 2 == 0) even.add(nums[j]);
            else odd.add(nums[j]);
            if (even.size() == odd.size())        // balanced window
                best = Math.max(best, j - i + 1);
        }
    }
    return best;
}
int longestBalanced(vector<int>& nums) {
    int n = nums.size(), best = 0;
    for (int i = 0; i < n; i++) {                 // fix the left end
        unordered_set<int> even, odd;
        for (int j = i; j < n; j++) {             // extend the right end
            if (nums[j] % 2 == 0) even.insert(nums[j]);
            else odd.insert(nums[j]);
            if (even.size() == odd.size())        // balanced window
                best = max(best, j - i + 1);
        }
    }
    return best;
}
Time: O(n²) Space: O(n)