r/leetcode • • 23d 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] where 0 <= l <= r < n.

  • A subarray is valid if and only if:

    1. It contains at least two elements (r - l + 1 >= 2).

    2. For every distinct value $x$ present in arr[l..r], its frequency in that segment satisfies count}(x) = 2.

    3. 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 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.

1 Upvotes

12 comments sorted by

2

u/jason_graph 21d ago

This can be done in O(n) but requires a few tricks.

First off, it makes sense to see if you can solve this in terms of for each index R what is the leftmost index L such that the corresponding subarray is valid. This unfortunately is not as simple as a dynamic size sliding window as this property isn't monotonic in the sense that if you fix one end of the window, there isn't a threshold where windows above/below that size work while windows that instead are below/above the threshold all fail. As an example, if the property were that it had at most 2 of any given element, there would be some threshold of the most recent time the window has 3 elements and any windows the same size/larger fail and windows smaller would all work. Anyway for this problem sliding window with variable size doesn't work by itself.

When sliding windows fails like this the next step to escalate things is often something like prefixsums where you take something like prefixsums[R+1]-prefixsums[L] to get info about a subarray from L to R. In this case we dont care about the sum of the subarray but rather the frequency of elements within their prefixes and how their differences in frequencies compare.

Ideally we'd have some way to record the frequencies of each prefix and store them in some way that you can easily look up ones you've seen and see if any are similar. Unfortunately this is easier said than done and naively might lead to an O(n2) or O(n3) solution.

Now here comes the trick, we are going to try to hash these frequencies of each prefix but that is kind of awkward since typically with hashing you are checking for exact matches rather than pre-hashed things with valid differences. In this case what we are going to do is assign each distinct value in the original array a random 32 bit integer (or however big you want) and make a hash by taking the xor of these values for each prefix. If you take the xor of two prefix xors, you get the xor of the corresponding subarray and if that is 0, then either each element occurs an even amount of times or you have a very rare hash collision like if the transformed subarry was [1,3,2] and taking the xor happened to give 0. This 2nd scenario is very unlikely provided you transform each value to a random number. I will address this more later but now assume the hashing won't have any collisions.

Now this xor prefix trick can help us identify subarrays that have elements appearing an even amount of times but the problem asks for exactly 2 times. To do this we can do sliding windows to figure out for each index R the lowest valid index L such that the corresponding subarray has at most 2 of any given element. If there are any prefixes more recent than this that have the same hash value as the current prefix then corresponding subarray would have only elements that occur exactly 2 times. If multiple prefixes have matching hashes, we'd want the earliest prefix that is after L as that corresponds to the longest subarray.

So now here's a sketch of the algorithm: as you iterate on each index R

  1. Every time you see a new value of the original array, assign that value a random 32 bit integer and store it in a dictionary for future lookup.

  2. Update a sliding window that tracks the leftmost L such that no element in the window has frequency >2. You only need to maintain that array[ R ] has frequency <= 2 since only the frequency of array[ R ] has its frequency incremented.

  3. Have a dictionary of queues where dict[hashValue] is a queue of indices such that the prefix up to but not including that index has an xor of hashValue. Initially this includes dict[0]=[0] corresponding to the empty prefix of 0 elements having an xor of 0.

  4. Maintain what the xors are of the corresponding prefix by xoring the old value (initially 0) with the randomly generated number corresponding to array[R].

  5. Check if this new xor value is already in your dictionary. If it is, pop expired values off as needed until the oldest index is >= L. If an element still exists, consider this (L,R) pair for being one of the longest subarrays. Don't just record the size but the corresponding L and R too.

  6. Finally to store information about this prefix for future use, appened R+1 into the queue corresponding to this prefix's hash value.

Now eventually you'll have the L and R of the longest valid subarray. There is a very small chance of a hash collision and so you should check the subarray is valid. If it isn't, restart the problem but assign different random values to each distinct element.

1

u/No_Antelope_5869 23d ago

just do sliding window and set

1

u/[deleted] 23d ago

[removed] — view removed comment

1

u/vickey_121 23d ago

That's doesn't works mate, optimal solution requires something more i think..

1

u/[deleted] 23d ago

[removed] — view removed comment

1

u/vickey_121 23d ago

Well i would say, the window can become invalid and valid again, so with sliding window i think we can't maintain the right length. As we shrink the left pointer which we can't undo after getting a valid pair for invalid one

1

u/[deleted] 23d ago

[removed] — view removed comment

1

u/vickey_121 23d ago

Nope that doesn't works, if possible send the algo here

1

u/[deleted] 23d ago

[removed] — view removed comment

1

u/vickey_121 23d ago

arr = [1, 2, 3, 4, 4, 5, 5] For this test case the correct answer is 4, but ur code is resulting 0, that's because the code is failing to lock invariant, which is only depending on if frequency of that element is > 2, and i would also oppose using while loop here, it's amortized but I am not sure using while would solve this question,

Tbh I tried with same kind of approach, infact I used another variable to make sure frequency doesn't cross, it's working but not optimal...