Write a segment tree in python
- User
Write a segment tree in python
- Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Write a segment tree in python
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
A segment tree is a data structure used for storing information about intervals or segments. It allows answering range queries over an array effectively, such as finding the minimum, maximum, sum, or greatest common divisor within a range, as well as updating values. It is particularly useful when there are many range queries on an immutable array.
Here's a simple Python implementation of a segment tree that calculates the sum of a range. This example includes both the tree construction and the query for sum in a given range:
class SegmentTree:
def __init__(self, nums):
self.n = len(nums)
self.tree = [0] * (2 * self.n)
self.build(nums)
def build(self, nums):
# Insert leaf nodes in the tree
for i in range(self.n, 2 * self.n):
self.tree[i] = nums[i - self.n]
# Build the tree by calculating parents
for i in range(self.n - 1, 0, -1):
self.tree[i] = self.tree[i << 1] + self.tree[i << 1 | 1]
def update(self, pos, val):
# Set value at position pos
pos += self.n
self.tree[pos] = val
while pos > 1:
# Move up and update parents
pos >>= 1
self.tree[pos] = self.tree[pos << 1] + self.tree[pos << 1 | 1]
def query(self, l, r):
# Query for the sum in the range [l, r)
l += self.n
r += self.n
result = 0
while l < r:
if l & 1:
result += self.tree[l]
l += 1
if r & 1:
r -= 1
result += self.tree[r]
l >>= 1
r >>= 1
return result
# Example usage
nums = [1, 3, 5, 7, 9, 11]
seg_tree = SegmentTree(nums)
print("Sum of values in range [1, 4):", seg_tree.query(1, 4)) # Output: 15
seg_tree.update(1, 10)
print("Sum of values in range [1, 4) after update:", seg_tree.query(1, 4)) # Output: 22
The key operations are:
Build: Construct the segment tree from the given array by filling the leaf nodes and then building the internal nodes by combining the children's values.
Update: Change the value at a specific position in the array and update the segment tree accordingly.
Query: Compute the sum of a range [l, r) using the segment tree.
This code assumes that the segment tree is 1-indexed for internal nodes, with children of node i being 2*i and 2*i+1, and that the leaves are stored in the second half of the array starting from index n to 2*n - 1. The logic shifts these indices to 0-based when accessing the tree array. The tree is built bottom-up, and queries and updates are performed in a top-down manner. The << 1 and >> 1 operations are bitwise shifts equivalent to multiplying or dividing by 2, respectively.