BudiBadu Logo

Longest Balanced Parity Subarray

Array Easy 0 views
Like19

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

Example 1
Input
nums = [2,5,6,3,4,7]
Output
"2,5,6,3,4,7"
Explanation

The entire array has three evens and three odds.

Example 2
Input
nums = [1,3,5,7]
Output
""
Explanation

No contiguous subarray balances even and odd counts.

Example 3
Input
nums = [2,4,1,3,6,8,5,7]
Output
"2,4,1,3,6,8,5,7"
Explanation

The full range contains four even and four odd numbers.

Algorithm Flow

Recommendation Algorithm Flow for Longest Balanced Parity Subarray - Budibadu
Recommendation Algorithm Flow for Longest Balanced Parity Subarray - Budibadu

Best Answers

java
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;
    }
}