Longest Balanced Parity Subarray
This problem looks for the longest continuous part of the list where the number of even values and odd values is exactly the same. That is what balanced parity means here.
The answer in this file is not a length. From the examples, the answer should be the balanced subarray written out as text, with the numbers joined by commas. If no balanced subarray exists, the answer should be an empty string. So you need to find the best stretch first, then return it in the right output format.
For example, [2,4,1,3,6,8,5,7] is balanced all the way through because it has four even numbers and four odd numbers, so the whole range is returned. But [1,3,5,7] has only odd numbers, so there is no balanced subarray and the answer is "".
The key detail is that the chosen part must stay contiguous. You are not picking numbers from different places. You are searching for the longest unbroken stretch where even and odd counts match perfectly.
Example Input & Output
The entire array has three evens and three odds.
No contiguous subarray balances even and odd counts.
The full range contains four even and four odd numbers.
Algorithm Flow

Best Answers
import java.util.*;
class Solution {
public int longest_balanced_parity_subarray(int[] nums) {
Map<Integer, Integer> map = new HashMap<>();
map.put(0, -1);
int maxLen = 0, current = 0;
for (int i = 0; i < nums.length; i++) {
current += (nums[i] % 2 == 0) ? 1 : -1;
if (map.containsKey(current)) maxLen = Math.max(maxLen, i - map.get(current));
else map.put(current, i);
}
return maxLen;
}
}Comments (0)
Join the Discussion
Share your thoughts, ask questions, or help others with this Challenge.
