Skip to content

Commit 42a7354

Browse files
putul03pre-commit-ci[bot]cclauss
authored
Persistent Segment Tree (#12186)
* Suffix Array and LCP Array Implementation * Delete divide_and_conquer/suffix_array_lcp.py * Add files via upload * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Update persistent_segment_tree.py * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Update persistent_segment_tree.py * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Update persistent_segment_tree.py * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Update persistent_segment_tree.py * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Update persistent_segment_tree.py * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Update persistent_segment_tree.py * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Update persistent_segment_tree.py * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Update persistent_segment_tree.py * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Update persistent_segment_tree.py * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Update persistent_segment_tree.py * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Update persistent_segment_tree.py * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Refactor Node class to use dataclass Refactor Node class to use dataclass for cleaner syntax. Update PersistentSegmentTree methods to maintain functionality with the new Node structure. * updating DIRECTORY.md * Refactor PersistentSegmentTree implementation * Refactor Node initialization and update methods Refactor Node class to properly initialize value and improve type hints. Update PersistentSegmentTree methods for better clarity and maintainability. * Apply suggestion from @cclauss * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Update persistent_segment_tree.py --------- Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com> Co-authored-by: Christian Clauss <cclauss@me.com> Co-authored-by: cclauss <cclauss@users.noreply.github.com>
1 parent 6161141 commit 42a7354

2 files changed

Lines changed: 139 additions & 0 deletions

File tree

‎DIRECTORY.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -304,6 +304,7 @@
304304
* [Mirror Binary Tree](data_structures/binary_tree/mirror_binary_tree.py)
305305
* [Non Recursive Segment Tree](data_structures/binary_tree/non_recursive_segment_tree.py)
306306
* [Number Of Possible Binary Trees](data_structures/binary_tree/number_of_possible_binary_trees.py)
307+
* [Persistent Segment Tree](data_structures/binary_tree/persistent_segment_tree.py)
307308
* [Red Black Tree](data_structures/binary_tree/red_black_tree.py)
308309
* [Segment Tree](data_structures/binary_tree/segment_tree.py)
309310
* [Segment Tree Other](data_structures/binary_tree/segment_tree_other.py)
Lines changed: 138 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,138 @@
1+
from __future__ import annotations
2+
3+
from dataclasses import dataclass
4+
5+
6+
@dataclass
7+
class Node:
8+
value: int
9+
left: Node | None = None
10+
right: Node | None = None
11+
12+
13+
class PersistentSegmentTree:
14+
def __init__(self, arr: list[int]) -> None:
15+
self.n: int = len(arr)
16+
self.roots: list[Node] = []
17+
self.roots.append(self._build(arr, 0, self.n - 1))
18+
19+
def _build(self, arr: list[int], start: int, end: int) -> Node:
20+
"""
21+
Builds a segment tree from the provided array.
22+
23+
>>> pst = PersistentSegmentTree([1, 2, 3, 4])
24+
>>> root = pst._build([1, 2, 3, 4], 0, 3)
25+
>>> root.value # Sum of the whole array
26+
10
27+
>>> root.left.value # Sum of the left half
28+
3
29+
>>> root.right.value # Sum of the right half
30+
7
31+
"""
32+
if start == end:
33+
return Node(arr[start])
34+
mid = (start + end) // 2
35+
left = self._build(arr, start, mid)
36+
right = self._build(arr, mid + 1, end)
37+
return Node(value=left.value + right.value, left=left, right=right)
38+
39+
def update(self, version: int, index: int, value: int) -> int:
40+
"""
41+
Updates the value at the given index and returns the new version.
42+
43+
>>> pst = PersistentSegmentTree([1, 2, 3, 4])
44+
>>> version_1 = pst.update(0, 1, 5) # Update index 1 to 5
45+
>>> pst.query(version_1, 0, 3) # Query sum of all elements in new version
46+
13
47+
>>> pst.query(0, 0, 3) # Original version remains unchanged
48+
10
49+
>>> version_2 = pst.update(version_1, 3, 6) # Update index 3 to 6 in version_1
50+
>>> pst.query(version_2, 0, 3) # Query sum of all elements in newest version
51+
15
52+
"""
53+
new_root = self._update(self.roots[version], 0, self.n - 1, index, value)
54+
self.roots.append(new_root)
55+
return len(self.roots) - 1
56+
57+
def _update(self, node: Node, start: int, end: int, index: int, value: int) -> Node:
58+
"""
59+
Update the node for the specified index and value and return the new node.
60+
61+
>>> pst = PersistentSegmentTree([1, 2, 3, 4])
62+
>>> old_root = pst.roots[0]
63+
>>> new_root = pst._update(old_root, 0, 3, 1, 5) # Update index 1 to 5
64+
>>> new_root.value # New sum after update
65+
13
66+
>>> old_root.value # Old root remains unchanged
67+
10
68+
>>> new_root.left.value # Updated left child
69+
6
70+
>>> new_root.right.value # Right child remains the same
71+
7
72+
"""
73+
if start == end:
74+
return Node(value)
75+
76+
mid = (start + end) // 2
77+
new_node = Node(0)
78+
79+
if index <= mid:
80+
new_node.left = self._update(node.left, start, mid, index, value)
81+
new_node.right = node.right # Ensure right node is the same as the original
82+
else:
83+
new_node.left = node.left # Ensure left node is the same as the original
84+
new_node.right = self._update(node.right, mid + 1, end, index, value)
85+
86+
new_node.value = new_node.left.value + (
87+
new_node.right.value if new_node.right else 0
88+
)
89+
90+
return new_node
91+
92+
def query(self, version: int, left: int, right: int) -> int:
93+
"""
94+
Queries the sum in the given range for the specified version.
95+
96+
>>> pst = PersistentSegmentTree([1, 2, 3, 4])
97+
>>> pst.query(0, 0, 3) # Sum of all elements in original version
98+
10
99+
>>> pst.query(0, 1, 2) # Sum of elements at index 1 and 2 in original version
100+
5
101+
>>> version_1 = pst.update(0, 1, 5) # Update index 1 to 5
102+
>>> pst.query(version_1, 0, 3) # Sum of all elements in new version
103+
13
104+
>>> pst.query(version_1, 1, 2) # Sum of elements at index 1 and 2
105+
8
106+
"""
107+
return self._query(self.roots[version], 0, self.n - 1, left, right)
108+
109+
def _query(self, node: Node, start: int, end: int, left: int, right: int) -> int:
110+
"""
111+
Queries the sum of values in the range [left, right] for the given node.
112+
113+
>>> pst = PersistentSegmentTree([1, 2, 3, 4])
114+
>>> root = pst.roots[0]
115+
>>> pst._query(root, 0, 3, 1, 2) # Sum of elements at index 1 and 2
116+
5
117+
>>> pst._query(root, 0, 3, 0, 3) # Sum of all elements
118+
10
119+
>>> pst._query(root, 0, 3, 2, 3) # Sum of elements at index 2 and 3
120+
7
121+
"""
122+
if node is None or left > end or right < start:
123+
return 0
124+
if left <= start and right >= end:
125+
return node.value
126+
mid = (start + end) // 2
127+
return self._query(node.left, start, mid, left, right) + self._query(
128+
node.right, mid + 1, end, left, right
129+
)
130+
131+
132+
# Running the doctests
133+
if __name__ == "__main__":
134+
import doctest
135+
136+
print("Running doctests...")
137+
result = doctest.testmod()
138+
print(f"Ran {result.attempted} tests, {result.failed} failed.")

0 commit comments

Comments
 (0)