Balanced Triplets Subarray
Balanced Triplets Subarray asks for the longest contiguous subarray that satisfies a triplet-balance rule across every length-3 window inside that subarray. In this dataset, windows containing only one parity (all-even or all-odd) break validity, while mixed-parity triplets are considered balanced enough to keep the streak alive.
A practical approach is to scan with a rolling check on each 3-element window. Extend the current candidate segment while the newest triplet is valid; when a violating triplet appears, restart from a safe position and continue. Track the best start/end span seen so far and return the actual subarray values for that best span. If no valid span exists, return an empty array.
Judge behavior confirms whole-array acceptance for certain mixed patterns, rejection for uniform-parity arrays, and empty output when no qualifying stretch is found. Return the selected subarray structure exactly as expected. The core difficulty is defining violation boundaries correctly so resets neither skip valid recovery points nor include invalid windows in the final returned segment.
Examples
Sliding windows like [1,2,3], [2,3,5], [3,5,4], [5,4,7] each contain exactly one even and two odd numbers.
No window of three values has the required mix.
The first seven readings sustain the one-even two-odd pattern across every triple.
Algorithm Flow

Best Answers
import java.util.*;
class Solution {
public int[] balanced_triplets_subarray(int[] nums) {
int n = nums.length;
if (n < 3) return new int[0];
boolean[] valid_starts = new boolean[n - 2];
for (int i = 0; i < n - 2; i++) {
int odd_cnt = 0;
for (int j = 0; j < 3; j++) {
if (nums[i+j] % 2 != 0) odd_cnt++;
}
if (odd_cnt == 2) valid_starts[i] = true;
}
int longest_len = 0;
int best_start = -1;
int current_start = -1;
int current_len = 0;
for (int i = 0; i < n - 2; i++) {
if (valid_starts[i]) {
if (current_len == 0) current_start = i;
current_len++;
} else {
if (current_len > 0) {
int real_len = current_len + 2;
if (real_len > longest_len) {
longest_len = real_len;
best_start = current_start;
}
}
current_len = 0;
}
}
if (current_len > 0) {
int real_len = current_len + 2;
if (real_len > longest_len) {
longest_len = real_len;
best_start = current_start;
}
}
if (best_start == -1) return new int[0];
return Arrays.copyOfRange(nums, best_start, best_start + longest_len);
}
}Comments (0)
Join the Discussion
Share your thoughts, ask questions, or help others with this problem.
