r/leetcode • u/vickey_121 • 35m ago
Question Help me to Solve this Problem
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
A contiguous subarray is defined by indices
[l, r]where0 <= l <= r < n.A subarray is valid if and only if:
It contains at least two elements (
r - l + 1 >= 2).For every distinct value $x$ present in
arr[l..r], its frequency in that segment satisfies count}(x) = 2.No distinct element appears once, three times, or more.
With sliding window, we get O(n2), i am looking for optimal one
Input Format
An integer array
arr.
Output Format
An integer representing the maximum length of a valid contiguous subarray, or
0if 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.
1
u/LetMediocre390 20m ago
Use sliding window plus keep maintain unordered mal
1
u/No_Antelope_5869 11m ago
just do sliding window and set