The problem is this, given an array of length say N
, we have to find all subsequences of length W
such that those W
elements, when sorted, forms an arithmetic progression with interval 1. So for an array like [1,4,6,3,5,2,7,9]
, and W
as 5, the slice [4,6,3,5,2]
can be regarded as one such subsequence, since, when sorted, it yields [2,3,4,5,6]
, an A.P with common difference 1.
The immediate solution which comes to the mind is to have a sliding window, for each new element, pop the old one, push the new one, sort the window, and if for that window, window[w-1] - window[0] + 1 = w
, then it is such a subsequence. However, it takes O(NlogN)
time, whereas the solution at Codechef proposes a O(N)
time algorithm that uses double-ended queue. I am having difficulty in understanding the algorithm, what is being pushed and popped, and why so, and how it maintains the window in sorted order without the need to resort with each new element. Can anybody explain it?