MCPcopy Create free account
hub / github.com/TheAlgorithms/Python / build_sparse_table

Function build_sparse_table

data_structures/arrays/sparse_table.py:17–58  ·  view source on GitHub ↗

Precompute range minimum queries with power of two length and store the precomputed values in a table. >>> build_sparse_table([8, 1, 0, 3, 4, 9, 3]) [[8, 1, 0, 3, 4, 9, 3], [1, 0, 0, 3, 4, 3, 0], [0, 0, 0, 3, 0, 0, 0]] >>> build_sparse_table([3, 1, 9]) [[3, 1, 9], [1, 1, 0]

(number_list: list[int])

Source from the content-addressed store, hash-verified

15
16
17def build_sparse_table(number_list: list[int]) -> list[list[int]]:
18 """
19 Precompute range minimum queries with power of two length and store the precomputed
20 values in a table.
21
22 >>> build_sparse_table([8, 1, 0, 3, 4, 9, 3])
23 [[8, 1, 0, 3, 4, 9, 3], [1, 0, 0, 3, 4, 3, 0], [0, 0, 0, 3, 0, 0, 0]]
24 >>> build_sparse_table([3, 1, 9])
25 [[3, 1, 9], [1, 1, 0]]
26 >>> build_sparse_table([])
27 Traceback (most recent call last):
28 ...
29 ValueError: empty number list not allowed
30 """
31 if not number_list:
32 raise ValueError("empty number list not allowed")
33
34 length = len(number_list)
35 # Initialise sparse_table -- sparse_table[j][i] represents the minimum value of the
36 # subset of length (2 ** j) of number_list, starting from index i.
37
38 # smallest power of 2 subset length that fully covers number_list
39 row = int(log2(length)) + 1
40 sparse_table = [[0 for i in range(length)] for j in range(row)]
41
42 # minimum of subset of length 1 is that value itself
43 for i, value in enumerate(number_list):
44 sparse_table[0][i] = value
45 j = 1
46
47 # compute the minimum value for all intervals with size (2 ** j)
48 while (1 << j) <= length:
49 i = 0
50 # while subset starting from i still have at least (2 ** j) elements
51 while (i + (1 << j) - 1) < length:
52 # split range [i, i + 2 ** j] and find minimum of 2 halves
53 sparse_table[j][i] = min(
54 sparse_table[j - 1][i + (1 << (j - 1))], sparse_table[j - 1][i]
55 )
56 i += 1
57 j += 1
58 return sparse_table
59
60
61def query(sparse_table: list[list[int]], left_bound: int, right_bound: int) -> int:

Callers 1

sparse_table.pyFile · 0.85

Calls

no outgoing calls

Tested by

no test coverage detected