Skip to content

Commit 52418f8

Browse files
hollowcrustpre-commit-ci[bot]cclauss
authored andcommitted
Added data_structures/arrays/sparse_table.py (TheAlgorithms#10437)
* Create sparse_table.py * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Descriptive names for variables * Fix ruff check error * Update sparse_table.py * Add comments, change variable names * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Fix typo * Update sparse_table.py --------- Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com> Co-authored-by: Christian Clauss <[email protected]>
1 parent cafd9c3 commit 52418f8

File tree

1 file changed

+94
-0
lines changed

1 file changed

+94
-0
lines changed

Diff for: data_structures/arrays/sparse_table.py

+94
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,94 @@
1+
"""
2+
Sparse table is a data structure that allows answering range queries on
3+
a static number list, i.e. the elements do not change throughout all the queries.
4+
5+
The implementation below will solve the problem of Range Minimum Query:
6+
Finding the minimum value of a subset [L..R] of a static number list.
7+
8+
Overall time complexity: O(nlogn)
9+
Overall space complexity: O(nlogn)
10+
11+
Wikipedia link: https://en.wikipedia.org/wiki/Range_minimum_query
12+
"""
13+
from math import log2
14+
15+
16+
def build_sparse_table(number_list: list[int]) -> list[list[int]]:
17+
"""
18+
Precompute range minimum queries with power of two length and store the precomputed
19+
values in a table.
20+
21+
>>> build_sparse_table([8, 1, 0, 3, 4, 9, 3])
22+
[[8, 1, 0, 3, 4, 9, 3], [1, 0, 0, 3, 4, 3, 0], [0, 0, 0, 3, 0, 0, 0]]
23+
>>> build_sparse_table([3, 1, 9])
24+
[[3, 1, 9], [1, 1, 0]]
25+
>>> build_sparse_table([])
26+
Traceback (most recent call last):
27+
...
28+
ValueError: empty number list not allowed
29+
"""
30+
if not number_list:
31+
raise ValueError("empty number list not allowed")
32+
33+
length = len(number_list)
34+
# Initialise sparse_table -- sparse_table[j][i] represents the minimum value of the
35+
# subset of length (2 ** j) of number_list, starting from index i.
36+
37+
# smallest power of 2 subset length that fully covers number_list
38+
row = int(log2(length)) + 1
39+
sparse_table = [[0 for i in range(length)] for j in range(row)]
40+
41+
# minimum of subset of length 1 is that value itself
42+
for i, value in enumerate(number_list):
43+
sparse_table[0][i] = value
44+
j = 1
45+
46+
# compute the minimum value for all intervals with size (2 ** j)
47+
while (1 << j) <= length:
48+
i = 0
49+
# while subset starting from i still have at least (2 ** j) elements
50+
while (i + (1 << j) - 1) < length:
51+
# split range [i, i + 2 ** j] and find minimum of 2 halves
52+
sparse_table[j][i] = min(
53+
sparse_table[j - 1][i + (1 << (j - 1))], sparse_table[j - 1][i]
54+
)
55+
i += 1
56+
j += 1
57+
return sparse_table
58+
59+
60+
def query(sparse_table: list[list[int]], left_bound: int, right_bound: int) -> int:
61+
"""
62+
>>> query(build_sparse_table([8, 1, 0, 3, 4, 9, 3]), 0, 4)
63+
0
64+
>>> query(build_sparse_table([8, 1, 0, 3, 4, 9, 3]), 4, 6)
65+
3
66+
>>> query(build_sparse_table([3, 1, 9]), 2, 2)
67+
9
68+
>>> query(build_sparse_table([3, 1, 9]), 0, 1)
69+
1
70+
>>> query(build_sparse_table([8, 1, 0, 3, 4, 9, 3]), 0, 11)
71+
Traceback (most recent call last):
72+
...
73+
IndexError: list index out of range
74+
>>> query(build_sparse_table([]), 0, 0)
75+
Traceback (most recent call last):
76+
...
77+
ValueError: empty number list not allowed
78+
"""
79+
if left_bound < 0 or right_bound >= len(sparse_table[0]):
80+
raise IndexError("list index out of range")
81+
82+
# highest subset length of power of 2 that is within range [left_bound, right_bound]
83+
j = int(log2(right_bound - left_bound + 1))
84+
85+
# minimum of 2 overlapping smaller subsets:
86+
# [left_bound, left_bound + 2 ** j - 1] and [right_bound - 2 ** j + 1, right_bound]
87+
return min(sparse_table[j][right_bound - (1 << j) + 1], sparse_table[j][left_bound])
88+
89+
90+
if __name__ == "__main__":
91+
from doctest import testmod
92+
93+
testmod()
94+
print(f"{query(build_sparse_table([3, 1, 9]), 2, 2) = }")

0 commit comments

Comments
 (0)