Editorial
First, coordinate-compress the values. Only equality between values matters, so this does not change the answer.
For every value , maintain:
- : the last position where occurs in the whole sequence;
- : the most recent occurrence of before the current position.
Suppose position is being processed and . Let . The answer is YES if there is a value such that
Indeed, setting and gives the required four positions. The strict inequality also guarantees .
Thus, among values that occur again after the current position, we need the largest recent occurrence position.
Whenever value occurs at position and , append to a stack. The appended positions are strictly increasing, so the valid pair with the largest position is always at the back of the stack.
Before processing position , repeatedly remove the last pair if either:
- , meaning a newer occurrence of has made the pair stale; or
- , meaning does not occur after position .
After these removals, the last pair stores the largest recent occurrence among all values that occur again later. Therefore, if has appeared before and the last stored position is greater than , the answer is YES.
To prove completeness, suppose
is a valid answer. Let be the first occurrence of after , and let be the previous occurrence of . Then
When processing , the recent occurrence of is at least , and its last occurrence is at least . Hence a valid pair with position greater than exists in the stack, so the algorithm detects the pattern.
Each pair is pushed and popped at most once. The scan after coordinate compression takes time. The total time complexity is and the memory complexity is .
Solution written by GPT5.6