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

Function create_sparse

data_structures/binary_tree/lowest_common_ancestor.py:27–53  ·  view source on GitHub ↗

creating sparse table which saves each nodes 2^i-th parent >>> max_node = 6 >>> parent = [[0, 0, 1, 1, 2, 2, 3]] + [[0] * 7 for _ in range(19)] >>> parent = create_sparse(max_node=max_node, parent=parent) >>> parent[0] [0, 0, 1, 1, 2, 2, 3] >>> parent[1] [0, 0, 0, 0,

(max_node: int, parent: list[list[int]])

Source from the content-addressed store, hash-verified

25
26
27def create_sparse(max_node: int, parent: list[list[int]]) -> list[list[int]]:
28 """
29 creating sparse table which saves each nodes 2^i-th parent
30 >>> max_node = 6
31 >>> parent = [[0, 0, 1, 1, 2, 2, 3]] + [[0] * 7 for _ in range(19)]
32 >>> parent = create_sparse(max_node=max_node, parent=parent)
33 >>> parent[0]
34 [0, 0, 1, 1, 2, 2, 3]
35 >>> parent[1]
36 [0, 0, 0, 0, 1, 1, 1]
37 >>> parent[2]
38 [0, 0, 0, 0, 0, 0, 0]
39
40 >>> max_node = 1
41 >>> parent = [[0, 0]] + [[0] * 2 for _ in range(19)]
42 >>> parent = create_sparse(max_node=max_node, parent=parent)
43 >>> parent[0]
44 [0, 0]
45 >>> parent[1]
46 [0, 0]
47 """
48 j = 1
49 while (1 << j) < max_node:
50 for i in range(1, max_node + 1):
51 parent[j][i] = parent[j - 1][parent[j - 1][i]]
52 j += 1
53 return parent
54
55
56# returns lca of node u,v

Callers 1

mainFunction · 0.85

Calls

no outgoing calls

Tested by

no test coverage detected