Tools
Tools: π Beginner-Friendly Guide 'Longest Balanced Subarray I' - Problem 3719 (C++, Python, JavaScript)
2026-02-10
0 views
admin
Problem Summary ## Intuition ## Walkthrough: Understanding the Examples ## C++ Solution ## Python Solution ## JavaScript Solution ## Key Takeaways ## Final Thoughts Navigating through arrays to find specific patterns is a fundamental skill for any developer. This problem challenges us to look beyond simple element counts and instead focus on the diversity of values within a contiguous range. It is a perfect exercise for mastering the use of hash sets to track uniqueness while iterating through data. 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. The core of this problem lies in the word "distinct." If a subarray contains the number 2 three times, it only counts as one distinct even number. To handle this efficiently, we can use a nested loop strategy to examine every possible subarray. For every starting position , we expand to every possible ending position . As we expand, we keep track of the unique even and odd numbers we have encountered using a "Set" or a "Hash Map." A Set is ideal here because it automatically handles duplicates for us: if we add the number 2 twice, the Set size only increases once. Whenever the size of our even set equals the size of our odd set, we have found a "balanced" subarray, and we update our maximum length. Let's look at Example 3: nums = [1, 2, 3, 2] Subarray [1, 2, 3, 2]: Even set = {2}, Odd set = {1, 3}. Sizes are . Start at index 1 (value 2): Subarray [2, 3]: Even set = {2}, Odd set = {3}. Sizes are . Length is 2. Subarray [2, 3, 2]: Even set = {2}, Odd set = {3}. Sizes are . Length is 3. (New Max) Start at index 2 (value 3): Subarray [3, 2]: Even set = {2}, Odd set = {3}. Sizes are . Length is 2. The longest length found is 3. This problem is a fantastic introduction to data integrity and filtering. In real-world systems, such as search engines or e-commerce filters, we often need to ensure that different categories of data are represented equally or meet specific ratio requirements. Mastering how to count unique occurrences while scanning through a stream of data is a skill you will use throughout your career. Templates let you quickly answer FAQs or store snippets for re-use. Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment's permalink. Hide child comments as well For further actions, you may consider blocking this person and/or reporting abuse COMMAND_BLOCK:
#include <vector>
#include <unordered_set>
#include <algorithm> 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]); } // Check if the number of distinct evens equals distinct odds if (even_set.size() == odd_set.size()) { max_ans = max(max_ans, j - i + 1); } } } return max_ans; }
}; Enter fullscreen mode Exit fullscreen mode COMMAND_BLOCK:
#include <vector>
#include <unordered_set>
#include <algorithm> 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]); } // Check if the number of distinct evens equals distinct odds if (even_set.size() == odd_set.size()) { max_ans = max(max_ans, j - i + 1); } } } return max_ans; }
}; COMMAND_BLOCK:
#include <vector>
#include <unordered_set>
#include <algorithm> 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]); } // Check if the number of distinct evens equals distinct odds if (even_set.size() == odd_set.size()) { max_ans = max(max_ans, j - i + 1); } } } return max_ans; }
}; COMMAND_BLOCK:
class Solution: def longestBalanced(self, nums: list[int]) -> int: 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]) # Compare the count of unique elements if len(even_set) == len(odd_set): max_ans = max(max_ans, j - i + 1) return max_ans Enter fullscreen mode Exit fullscreen mode COMMAND_BLOCK:
class Solution: def longestBalanced(self, nums: list[int]) -> int: 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]) # Compare the count of unique elements if len(even_set) == len(odd_set): max_ans = max(max_ans, j - i + 1) return max_ans COMMAND_BLOCK:
class Solution: def longestBalanced(self, nums: list[int]) -> int: 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]) # Compare the count of unique elements if len(even_set) == len(odd_set): max_ans = max(max_ans, j - i + 1) return max_ans CODE_BLOCK:
/** * @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]); } // In JS, we use .size to get the number of unique elements if (evenSet.size === oddSet.size) { maxAns = Math.max(maxAns, j - i + 1); } } } return maxAns;
}; Enter fullscreen mode Exit fullscreen mode CODE_BLOCK:
/** * @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]); } // In JS, we use .size to get the number of unique elements if (evenSet.size === oddSet.size) { maxAns = Math.max(maxAns, j - i + 1); } } } return maxAns;
}; CODE_BLOCK:
/** * @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]); } // In JS, we use .size to get the number of unique elements if (evenSet.size === oddSet.size) { maxAns = Math.max(maxAns, j - i + 1); } } } return maxAns;
}; - Start at index 0 (value 1):
- Subarray [1, 2]: Even set = {2}, Odd set = {1}. Sizes are . Length is 2.
- Subarray [1, 2, 3]: Even set = {2}, Odd set = {1, 3}. Sizes are .
- Subarray [1, 2, 3, 2]: Even set = {2}, Odd set = {1, 3}. Sizes are .
- Start at index 1 (value 2):
- Subarray [2, 3]: Even set = {2}, Odd set = {3}. Sizes are . Length is 2.
- Subarray [2, 3, 2]: Even set = {2}, Odd set = {3}. Sizes are . Length is 3. (New Max)
- Start at index 2 (value 3):
- Subarray [3, 2]: Even set = {2}, Odd set = {3}. Sizes are . Length is 2. - Set Data Structures: Using a Set is the most efficient way to track "distinct" or "unique" items because it ignores duplicate entries automatically.
- Subarray Brute Force: For smaller constraints (like ), an approach using nested loops is often acceptable and much easier to implement than complex sliding windows.
- Parity Logic: Using the modulo operator % 2 is the standard way to distinguish between even and odd numbers in programming.
how-totutorialguidedev.toaipythonjavascript