Skip to content
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

Added Segment tree #12594

Open
wants to merge 5 commits into
base: master
Choose a base branch
from
Open
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
[pre-commit.ci] auto fixes from pre-commit.com hooks
for more information, see https://pre-commit.ci
  • Loading branch information
pre-commit-ci[bot] committed Feb 28, 2025
commit 8e16739d525ccbe5cfd03879ebdcae31bf47f43b
15 changes: 9 additions & 6 deletions searches/segment_tree.py
Original file line number Diff line number Diff line change
Expand Up @@ -83,6 +83,7 @@
Query both the children and add their results and return that
"""


class SegmentTree:
def __init__(self, arr, merge_func, default):
"""
Expand All @@ -97,7 +98,7 @@ def __init__(self, arr, merge_func, default):
self.n = len(arr)

# while self.n is not a power of two
while (self.n & (self.n-1)) != 0:
while (self.n & (self.n - 1)) != 0:
self.n += 1
self.arr.append(default)

Expand All @@ -109,8 +110,9 @@ def __init__(self, arr, merge_func, default):
self.segment_tree[self.n + i] = arr[i]

for i in range(self.n - 1, 0, -1):
self.segment_tree[i] = self.merge_func(self.segment_tree[2 * i],
self.segment_tree[2 * i + 1])
self.segment_tree[i] = self.merge_func(
self.segment_tree[2 * i], self.segment_tree[2 * i + 1]
)

def update(self, index, value):
"""
Expand All @@ -120,8 +122,9 @@ def update(self, index, value):

while index >= 1:
index //= 2 # Go to the parent of index
self.segment_tree[index] = self.merge_func(self.segment_tree[2 * index],
self.segment_tree[2 * index + 1])
self.segment_tree[index] = self.merge_func(
self.segment_tree[2 * index], self.segment_tree[2 * index + 1]
)

def query(self, left, right, node_index=1, node_left=0, node_right=None):
"""
Expand All @@ -148,5 +151,5 @@ def query(self, left, right, node_index=1, node_left=0, node_right=None):
# of the query values of both the children nodes
return self.merge_func(
self.query(left, right, node_index * 2, node_left, mid),
self.query(left, right, node_index * 2 + 1, mid + 1, node_right)
self.query(left, right, node_index * 2 + 1, mid + 1, node_right),
)