Sparse Table Algorithm
(追記ここまで)(追記) (追記ここまで)(追記)Sparse table method supports query time O(1) with extra space O(n Log n).
(追記ここまで)(追記)The idea is to precompute minimum of all subarrays of size 2j where j varies from 0 to Log n. Like method 1, we make a lookup table. Here ~lookup[i][j] contains minimum of range starting from i and of size 2j. For example ~lookup[0][3] contains minimum of range [0, 7] (starting with 0 and of size 23)
(追記ここまで)(追記)Preprocessing
(追記ここまで)(追記) (追記ここまで)(追記)How to fill this lookup table? The idea is simple, fill in bottom up manner using previously computed values.
(追記ここまで)(追記)For example, to find minimum of range [0, 7], we can use minimum of following two.
(追記ここまで)- Minimum of range [0, 3]
- Minimum of range [4, 7]
Based on above example, below is formula,
(追記ここまで)(追記)If ~arr[lookup[i][j-1]] <= ~arr[lookup[i+2j-1-1][j-1]] ~lookup[i][j] = ~lookup[i][j-1]
(追記ここまで)(追記)Else ~lookup[i][j] = ~lookup[i+2j-1-1][j-1]
(追記ここまで)(追記) (追記ここまで)(追記)Query
(追記ここまで)(追記) (追記ここまで)(追記)For any arbitrary range [l, R], we need to use ranges which are in powers of 2. The idea is to use closest power of 2. We always need to do at most one comparison (compare minimum of two ranges which are powers of 2). One range starts with L and and ends with "L + closest-power-of-2". The other range ends at R and starts with "R – same-closest-power-of-2 + 1". For example, if given range is (2, 10), we compare minimum of two ranges (2, 9) and (3, 10).
(追記ここまで)(追記)j = floor(Log(R-L+1))
(追記ここまで)(追記)If ~arr[lookup[L][j]] <= ~arr[lookup[R-(int)pow(2,j)+1][j]] RMQ(L, R) = ~lookup[L][j]
(追記ここまで)(追記)Else RMQ(L, R) = ~lookup[i+2j-1-1][j-1]
(追記ここまで)(追記)Since we do only one comparison, time complexity of query is O(1).
(追記ここまで)