🐂 Beginner-Friendly Guide 'Longest Balanced Subarray I' - Problem 3719 (C++, Python, JavaScript)
Source: Dev.to

Problem Summary
You’re given:
An array of integers called nums.
Your goal:
Find the length of the longest subarray where the count of distinct even numbers is exactly equal to the count of distinct odd numbers.
Intuition
The key is the word distinct. If a subarray contains the number 2 three times, it counts as only one distinct even number.
A straightforward way is to examine every possible subarray with a nested loop:
- For each starting index
i, expand to every possible ending indexj. - While expanding, keep two sets (or hash maps) – one for unique even numbers and one for unique odd numbers.
- Whenever the sizes of the two sets are equal, we have a balanced subarray; update the maximum length.
Walkthrough: Understanding the Example
Example 3: nums = [1, 2, 3, 2]
-
Start at index 0 (value 1)
- Subarray
[1, 2]: even ={2}, odd ={1}→ balanced, length = 2 - Subarray
[1, 2, 3]: even ={2}, odd ={1, 3}→ not balanced - Subarray
[1, 2, 3, 2]: even ={2}, odd ={1, 3}→ not balanced
- Subarray
-
Start at index 1 (value 2)
- Subarray
[2, 3]: even ={2}, odd ={3}→ balanced, length = 2 - Subarray
[2, 3, 2]: even ={2}, odd ={3}→ balanced, length = 3 (new max)
- Subarray
-
Start at index 2 (value 3)
- Subarray
[3, 2]: even ={2}, odd ={3}→ balanced, length = 2
- Subarray
The longest balanced subarray length is 3.
C++ Solution
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
int longestBalanced(vector<int>& nums) {
int max_ans = 0;
int n = nums.size();
// Check every possible starting point
for (int i = 0; i < n; ++i) {
unordered_set<int> even_set;
unordered_set<int> odd_set;
// Expand the subarray to every possible ending point
for (int j = i; j < n; ++j) {
if (nums[j] % 2 == 0) {
even_set.insert(nums[j]);
} else {
odd_set.insert(nums[j]);
}
// Update answer when distinct counts match
if (even_set.size() == odd_set.size()) {
max_ans = max(max_ans, j - i + 1);
}
}
}
return max_ans;
}
};
Python Solution
def longestBalanced(nums):
max_ans = 0
n = len(nums)
# Outer loop sets the start of the subarray
for i in range(n):
even_set = set()
odd_set = set()
# Inner loop expands the end of the subarray
for j in range(i, n):
if nums[j] % 2 == 0:
even_set.add(nums[j])
else:
odd_set.add(nums[j])
# Update answer when distinct counts match
if len(even_set) == len(odd_set):
max_ans = max(max_ans, j - i + 1)
return max_ans
JavaScript Solution
/**
* @param {number[]} nums
* @return {number}
*/
var longestBalanced = function(nums) {
let maxAns = 0;
const n = nums.length;
for (let i = 0; i < n; i++) {
let evenSet = new Set();
let oddSet = new Set();
for (let j = i; j < n; j++) {
if (nums[j] % 2 === 0) {
evenSet.add(nums[j]);
} else {
oddSet.add(nums[j]);
}
// Update answer when distinct counts match
if (evenSet.size === oddSet.size) {
maxAns = Math.max(maxAns, j - i + 1);
}
}
}
return maxAns;
};
Key Takeaways
- Set Data Structures: Sets automatically ignore duplicate entries, making them ideal for tracking distinct elements.
- Brute‑Force Subarray Scan: For modest input sizes, the nested‑loop approach is simple and sufficient; more advanced sliding‑window techniques are unnecessary.
- Parity Check: Using the modulo operator (
% 2) cleanly separates even and odd numbers in most languages.
Final Thoughts
This problem introduces the concept of balancing distinct categories within a contiguous range—a pattern that appears in real‑world scenarios such as search engine indexing or e‑commerce filtering, where different attribute groups must be represented equally. Mastering the use of sets to count unique occurrences while scanning data is a valuable skill that will serve you throughout your programming career.