Say I have an array of integers A
of length N
, also I have an integer L
<= N
.
What I am trying to find is the minimum of the range [0, L-1], [1,L], [2,L+1]....[N-L,N-1]
(like a moving window of length L
from left to right)
My algorithm now is O(N lg N) with O(N lg N) preprocess:
- Save all numbers
A[0...L-1]
in a multi-setS
, also store the number in a queueQ
in order. The minimum of [0, L-1] is simply the first element ofS
. O(N lg N) - Pop out the first element of
Q
, find this element inS
and delete it. Then pushA[L]
inS
. The minimum of [1, L] is simply the first element ofS
. O(lg N) - Repeat step 2 for all possible range, move to next element each iteration. O(N)
Total is O(N lg N).
I wonder if there is any algorithm which can achieve better than this with following requirements:
- Preprocess time (If needed) is O(N)
- Query time if O(1)
I have done some research on RMQ, the nearest method I found is using sparse table which achieve O(1) query time but O(N lg N) preprocess time. Another method which reduce RMQ to LCA problem can meet the requirements but it needs some restriction on the array A
.
So is it possible that, with no restriction on A
, the requirements can be fulfilled when solving my problem?