Code Logo

Longest Balanced Parity Subarray

Published atDate not available
Easy 0 views
Like0

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

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
Recommendation Algorithm Flow for Longest Balanced Parity Subarray

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