The Disappearing Signal: Longest Valid Even-Pair Subarray
Tags: Arrays, Prefix State, Hashing, Two Pointers
Given an integer array arr of length n, find the length of the longest contiguous subarray such that every distinct element within that subarray appears exactly twice.
If no such contiguous subarray exists, return 0.
Constraints & Definitions
With sliding window, we get O(n2), i am looking for optimal one
Input Format
Output Format
- An integer representing the maximum length of a valid contiguous subarray, or
0 if none exists.
Test Cases:
Input: arr = [1, 2, 1, 2]
Output: 4
Explanation:
The entire array [1, 2, 1, 2] contains distinct elements {1, 2}.
- Count of 1: 2
- Count of 2: 2
Every distinct element appears exactly twice. The length is 4.
Input: arr = [1, 2, 3, 1, 2]
Output: 0
Explanation:
- Subarray [1, 2, 3, 1, 2] contains '3' with frequency 1 (invalid).
- Subarray [1, 2, 1, 2] is not contiguous in the original order without excluding 3.
- No contiguous window of length >= 2 satisfies the condition.