
Problem
Solution
Submissions
Segment Tree for Range Queries
Certification: Advanced Level
Accuracy: 100%
Submissions: 2
Points: 15
Write a Python class SegmentTree
that implements a segment tree data structure for efficient range queries. The segment tree should support the following operations:
- Build a segment tree from an array
- Update a single element in the segment tree
- Query for the sum of elements in a given range
Example 1
- Input: arr = [1, 3, 5, 7, 9, 11], query(1, 3)
- Output: 15
- Explanation:
- Step 1: Build segment tree for array [1, 3, 5, 7, 9, 11].
- Step 2: Query for sum from index 1 to 3.
- Step 3: Elements at indices 1, 2, 3 are 3, 5, and 7 respectively.
- Step 4: Return 3 + 5 + 7 = 15.
Example 2
- Input: arr = [1, 3, 5, 7, 9, 11], update(1, 10), query(1, 3)
- Output: 22
- Explanation:
- Step 1: Build segment tree for array [1, 3, 5, 7, 9, 11].
- Step 2: Update index 1 to value 10 → array becomes [1, 10, 5, 7, 9, 11].
- Step 3: Query for sum from index 1 to 3.
- Step 4: Return 10 + 5 + 7 = 22.
Constraints
- 1 ≤ arr.length ≤ 105
- -104 ≤ arr[i] ≤ 104
- 0 ≤ left ≤ right < arr.length
- Time Complexity: Build - O(n), Query - O(log n), Update - O(log n)
- Space Complexity: O(n)
Editorial
My Submissions
All Solutions
Lang | Status | Date | Code |
---|---|---|---|
You do not have any submissions for this problem. |
User | Lang | Status | Date | Code |
---|---|---|---|---|
No submissions found. |
Solution Hints
- Design a recursive function to build the segment tree
- For query operations, check if the current range completely overlaps with the query range
- For update operations, recursively update all affected nodes
- Store the segment tree in an array of size 4*n
- Handle edge cases like empty arrays or invalid ranges