Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Sparse table algorithm #219
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Sparse table algorithm #219
Changes from all commits
ce313ff
60f951c
c47eef5
4462095
File filter
Filter by extension
Conversations
Jump to
There are no files selected for viewing
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.
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).