Longest Balanced Subarray
In a field experiment, some entries capture calm intervals (even numbers) while others reflect fluctuations (odd numbers). Your goal in Longest Balanced Subarray is to find the longest contiguous segment where these two states appear in Perfect Balance—meaning the number of even elements equals the number of odd elements.
The "secret sauce" here is a Prefix Difference Tracker. Treat each even number as a +1 and each odd number as a -1. As you walk the array, keep a running total of the balance. If you hit a balance value (like 3) that you've seen before at an earlier index, it means the section between those two points is perfectly balanced! By storing the first occurrence of each balance in a map, you can find the maximum length in a single O(n) pass. Negative numbers and duplicates follow the same parity logic. This allows the team to pinpoint the longest harmonized stretch in the lab data instantly! Return the length of that stretch as an integer.
Examples
The entire array has three evens and three odds, forming the longest balanced subarray.
There is no subarray where even and odd counts match.
The full array balances four even numbers with four odd numbers.
Algorithm Flow

Best Answers
import java.util.*;
class Solution {
public int find_longest_balanced_segment(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++) {
if (nums[i] > 0) current++;
else if (nums[i] < 0) current--;
else continue;
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.
