Tutorialspoint
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:

  1. Build a segment tree from an array
  2. Update a single element in the segment tree
  3. 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
  • -104arr[i] ≤ 104
  • 0 ≤ leftright < arr.length
  • Time Complexity: Build - O(n), Query - O(log n), Update - O(log n)
  • Space Complexity: O(n)
RecursionTreeGoogleeBay
Editorial

Login to view the detailed solution and explanation for this problem.

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.

Please Login to continue
Solve Problems

 
 
 
Output Window

Don't have an account? Register

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

Steps to solve by this approach:

 Step 1: Create a segment tree class with methods for building, querying, and updating.
 Step 2: Build the segment tree recursively, where each node stores the sum of elements in its range.
 Step 3: For query operations, recursively find the sum of elements in the specified range.
 Step 4: For update operations, recursively update the value and recalculate sums for affected nodes.
 Step 5: Use helper functions to handle recursion for both query and update operations.

Submitted Code :