Longest Balanced Parity Subarray
Longest Balanced Parity Subarray returns the maximum length of a contiguous segment with equal counts of even and odd numbers. In this dataset, the expected output is a length integer, not the subarray values. If no balanced segment exists, return zero.
The reliable method is prefix-difference mapping. Convert each element conceptually into +1 for even and -1 for odd, then track cumulative difference while scanning. When the same cumulative difference appears again, the segment between those positions has net zero difference, meaning equal even/odd count. Store earliest index of each difference to maximize segment length.
Judge coverage includes fully balanced arrays, mostly-one-parity arrays, mixed arrays with long balanced interiors, and empty input. Return only the maximum length integer. Complexity is linear with hash map support. Correctness depends on initializing difference zero at index -1 so prefixes that are already balanced are counted correctly. This pattern is a standard template for equal-count subarray detection under binary category transforms.
If no zero-difference span is found, return zero rather than negative or null values. In practical terms, this means initializing best length to zero and only updating when a valid repeated-difference boundary is detected, including the prefix-balanced case starting at index zero.
Examples
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 problem.
