The Wayback Machine - https://web.archive.org/web/20240816083904/https://www.geeksforgeeks.org/implement-simple-2d-segment-tree-in-python/
Open In App

Implement Simple 2D Segment Tree in Python

Last Updated : 01 Jun, 2024
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

A 2D Segment Tree is a data structure that allows efficient querying and updating of two-dimensional arrays, such as matrices. It’s an extension of the 1D segment tree, allowing range queries and updates in 2D. Here’s a step-by-step implementation of a simple 2D Segment Tree in Python. We’ll focus on building the segment tree, querying for the sum of a submatrix, and updating an element in the matrix.

Implementation of Simple 2D Segment Tree in Python

Step 1: Define the Segment Tree Node

First, let’s define a class to represent each node of the 2D segment tree. Each node will store the sum of elements in its corresponding submatrix.

Python
class SegmentTree2D:
    def __init__(self, matrix):
        if not matrix or not matrix[0]:
            return
        
        self.n = len(matrix)
        self.m = len(matrix[0])
        self.tree = [[0] * (2 * self.m) for _ in range(2 * self.n)]
        self.build(matrix)
    
    def build(self, matrix):
        # Build the segment tree
        for i in range(self.n):
            for j in range(self.m):
                self.tree[i + self.n][j + self.m] = matrix[i][j]
        
        # Build columns
        for i in range(self.n):
            for j in range(self.m - 1, 0, -1):
                self.tree[i + self.n][j] = self.tree[i + self.n][2 * j] + self.tree[i + self.n][2 * j + 1]
        
        # Build rows
        for i in range(self.n - 1, 0, -1):
            for j in range(2 * self.m):
                self.tree[i][j] = self.tree[2 * i][j] + self.tree[2 * i + 1][j]

Step 2: Update Operation

Next, let’s implement the update operation to modify the value of a specific element in the matrix.

Python
    def update(self, row, col, val):
        # Update the value at (row, col) to val
        r, c = row + self.n, col + self.m
        self.tree[r][c] = val
        
        # Update columns
        while c > 1:
            c //= 2
            self.tree[r][c] = self.tree[r][2 * c] + self.tree[r][2 * c + 1]
        
        # Update rows
        while r > 1:
            r //= 2
            c = col + self.m
            while c >= 1:
                self.tree[r][c] = self.tree[2 * r][c] + self.tree[2 * r + 1][c]
                c //= 2

Step 3: Range Sum Query

Now, let’s implement the range sum query operation to calculate the sum of elements in a submatrix.

Python
    def sum_region(self, row1, col1, row2, col2):
        # Get the sum of the elements in the submatrix [(row1, col1), (row2, col2)]
        res = 0
        r1, r2 = row1 + self.n, row2 + self.n + 1
        while r1 < r2:
            if r1 % 2 == 1:
                res += self.sum_col(r1, col1, col2)
                r1 += 1
            if r2 % 2 == 1:
                r2 -= 1
                res += self.sum_col(r2, col1, col2)
            r1 //= 2
            r2 //= 2
        return res
    
    def sum_col(self, row, col1, col2):
        res = 0
        c1, c2 = col1 + self.m, col2 + self.m + 1
        while c1 < c2:
            if c1 % 2 == 1:
                res += self.tree[row][c1]
                c1 += 1
            if c2 % 2 == 1:
                c2 -= 1
                res += self.tree[row][c2]
            c1 //= 2
            c2 //= 2
        return res

Step 4: Example Usage

Finally, let’s provide an example of how to use the 2D segment tree for updating and querying.

Python
# Example usage
matrix = [
    [1, 2, 3],
    [4, 5, 6],
    [7, 8, 9]
]

st = SegmentTree2D(matrix)
print(st.sum_region(0, 0, 1, 1))  # Sum of submatrix from (0,0) to (1,1)
st.update(1, 1, 10)
print(st.sum_region(0, 0, 1, 1))  # Sum of submatrix from (0,0) to (1,1) after update

2D Segment Tree in Python

Python
class SegmentTree2D:
    def __init__(self, matrix):
        if not matrix or not matrix[0]:
            return
        
        self.n = len(matrix)
        self.m = len(matrix[0])
        self.tree = [[0] * (2 * self.m) for _ in range(2 * self.n)]
        self.build(matrix)
    
    def build(self, matrix):
        # Build the segment tree
        for i in range(self.n):
            for j in range(self.m):
                self.tree[i + self.n][j + self.m] = matrix[i][j]
        
        # Build columns
        for i in range(self.n):
            for j in range(self.m - 1, 0, -1):
                self.tree[i + self.n][j] = self.tree[i + self.n][2 * j] + self.tree[i + self.n][2 * j + 1]
        
        # Build rows
        for i in range(self.n - 1, 0, -1):
            for j in range(2 * self.m):
                self.tree[i][j] = self.tree[2 * i][j] + self.tree[2 * i + 1][j]
    
    def update(self, row, col, val):
        # Update the value at (row, col) to val
        r, c = row + self.n, col + self.m
        self.tree[r][c] = val
        
        # Update columns
        while c > 1:
            c //= 2
            self.tree[r][c] = self.tree[r][2 * c] + self.tree[r][2 * c + 1]
        
        # Update rows
        while r > 1:
            r //= 2
            c = col + self.m
            while c >= 1:
                self.tree[r][c] = self.tree[2 * r][c] + self.tree[2 * r + 1][c]
                c //= 2
    
    def sum_region(self, row1, col1, row2, col2):
        # Get the sum of the elements in the submatrix [(row1, col1), (row2, col2)]
        res = 0
        r1, r2 = row1 + self.n, row2 + self.n + 1
        while r1 < r2:
            if r1 % 2 == 1:
                res += self.sum_col(r1, col1, col2)
                r1 += 1
            if r2 % 2 == 1:
                r2 -= 1
                res += self.sum_col(r2, col1, col2)
            r1 //= 2
            r2 //= 2
        return res
    
    def sum_col(self, row, col1, col2):
        res = 0
        c1, c2 = col1 + self.m, col2 + self.m + 1
        while c1 < c2:
            if c1 % 2 == 1:
                res += self.tree[row][c1]
                c1 += 1
            if c2 % 2 == 1:
                c2 -= 1
                res += self.tree[row][c2]
            c1 //= 2
            c2 //= 2
        return res

# Example usage
matrix = [
    [1, 2, 3],
    [4, 5, 6],
    [7, 8, 9]
]

st = SegmentTree2D(matrix)
print(st.sum_region(0, 0, 1, 1))  # Sum of submatrix from (0,0) to (1,1)
st.update(1, 1, 10)
print(st.sum_region(0, 0, 1, 1))  # Sum of submatrix from (0,0) to (1,1) after update

Output
12
17




Similar Reads

Find middle point segment from given segment lengths
Given an array arr[] of size M. The array represents segment lengths of different sizes. These segments divide a line beginning with 0. The value of arr[0] represents a segment from 0 arr[0], value of arr[1] represents segment from arr[0] to arr[1], and so on. The task is to find the segment which contains the middle point, If the middle segment do
6 min read
Build a segment tree for N-ary rooted tree
Prerequisite: Segment tree and depth first search.In this article, an approach to convert an N-ary rooted tree( a tree with more than 2 children) into a segment tree is discussed which is used to perform a range update queries. Why do we need a segment tree when we already have an n-ary rooted tree? Many times, a situation occurs where the same ope
15+ min read
Cartesian tree from inorder traversal | Segment Tree
Given an in-order traversal of a cartesian tree, the task is to build the entire tree from it. Examples: Input: arr[] = {1, 5, 3} Output: 1 5 3 5 / \ 1 3 Input: arr[] = {3, 7, 4, 8} Output: 3 7 4 8 8 / 7 / \ 3 4 Approach: We have already seen an algorithm here that takes O(NlogN) time on an average but can get to O(N2) in the worst case.In this art
13 min read
Comparison between Fenwick Tree vs Segment Tree - with Similarities and Differences
Fenwick Tree (Binary Indexed Tree) and Segment Tree are both data structures used for efficient range query and update operations on an array. Here's a tabular comparison of these two data structures. Similarities between the Fenwick tree and Segment treeHere are some of the areas where Fenwick Tree is similar to Segment Tree: Array type: Both Fenw
2 min read
Overview of Graph, Trie, Segment Tree and Suffix Tree Data Structures
Introduction:Graph: A graph is a collection of vertices (nodes) and edges that represent relationships between the vertices. Graphs are used to model and analyze networks, such as social networks or transportation networks.Trie: A trie, also known as a prefix tree, is a tree-like data structure that stores a collection of strings. It is used for ef
10 min read
Can we use Simple Queue instead of Priority queue to implement Dijkstra's Algorithm?
What is Dijkstra's Algorithm? Dijkstra's Algorithm is used for finding the shortest path between any two vertices of a graph. It uses a priority queue for finding the shortest path. For more detail, about Dijkstra's Algorithm, you can refer to this article. Why Dijkstra's Algorithm uses a Priority Queue? We use min heap in Dijkstra's Algorithm beca
2 min read
Persistent Segment Tree in Python
Persistent data structures are a powerful tool in computer science, enabling us to maintain and access multiple versions of a data structure over time. One such structure is the Persistent Segment Tree. Segment trees are versatile data structures that allow efficient querying and updating of array intervals. By making a segment tree persistent, we
9 min read
Compression of 2D Segment Tree in Python
Compressing a 2D segment tree in Python involves reducing memory usage by storing only necessary information. This can be achieved by employing various techniques such as segment tree compression and lazy propagation. Let's create a tutorial on compressing a 2D segment tree in Python. A 2D segment tree is a data structure used for efficient queryin
5 min read
Segment Tree | (XOR of a given range )
Let us consider the following problem to understand Segment Trees.We have an array arr[0 . . . n-1]. We should be able to 1 Find the xor of elements from index l to r where 0 &lt;= l &lt;= r &lt;= n-1.2 Change value of a specified element of the array to a new value x. We need to do arr[i] = x where 0 &lt;= i &lt;= n-1.Similar to Sum of Given Range
15+ min read
Levelwise Alternating OR and XOR operations in Segment Tree
A Levelwise OR/XOR alternating segment tree is a segment tree, such that at every level the operations OR and XOR alternate. In other words at Level 1 the left and right sub-trees combine together by the OR operation i.e Parent node = Left Child OR Right Child and on Level 2 the left and right sub-trees combine together by the XOR operation i.e Par
15+ min read
Segment Tree | Set 2 (Range Maximum Query with Node Update)
Given an array arr[0 . . . n-1]. Find the maximum of elements from index l to r where 0 &lt;= l &lt;= r &lt;= n-1. Also, change the value of a specified element of the array to a new value x. We need to do arr[i] = x where 0 &lt;= i &lt;= n-1 and then find the maximum element of given range with updated values.Example : Input : {1, 3, 5, 7, 9, 11}
15+ min read
Levelwise Alternating GCD and LCM of nodes in Segment Tree
A Levelwise GCD/LCM alternating segment tree is a segment tree, such that at every level the operations GCD and LCM alternate. In other words at Level 1 the left and right sub-trees combine together by the GCD operation i.e Parent node = Left Child GCD Right Child and on Level 2 the left and right sub-trees combine together by the LCM operation i.e
15+ min read
Iterative Segment Tree (Range Maximum Query with Node Update)
Given an array arr[0 . . . n-1]. The task is to perform the following operation: Find the maximum of elements from index l to r where 0 &lt;= l &lt;= r &lt;= n-1.Change value of a specified element of the array to a new value x. Given i and x, change A[i] to x, 0 &lt;= i &lt;= n-1. Examples: Input: a[] = {2, 6, 7, 5, 18, 86, 54, 2} Query1: maximum(
14 min read
Iterative Segment Tree (Range Minimum Query)
We have discussed recursive segment tree implementation. In this post, iterative implementation is discussed.Let us consider the following problem understand Segment Trees. We have an array arr[0 . . . n-1]. We should be able to Find the minimum of elements from index l to r where 0 &lt;= l &lt;= r &lt;= n-1 Change value of a specified element of t
14 min read
Counting inversions in an array using segment tree
Given an array of integers arr, the task is to count the number of inversions in the array. If A[i] &gt; A[j] and i &lt; j then the pair (A[i], A[j]) is part of an inversion. Examples: Input: arr[] = {8, 4, 2, 1} Output: 6 Input: arr[] = {3, 1, 2} Output: 2 Approach: Build a segment tree where each node will represent the total numbers present in t
10 min read
Range Update without using Lazy Propagation and Point Query in a Segment Tree
Given an array arr[] consisting of N 0s and a 2D array Q[][] consisting of queries of the following two types: 1 L R X: Increment all the elements in the range [L, R] by X.2 X: Print elements at Xth index of the array. Input: arr[] = { 0, 0, 0, 0, 0 }, Q[][] = { { 1, 0, 2, 100 }, { 2, 1 }, { 1, 2, 3, 200 }, { 2, 2 }, { 4 } } Output: 100 300 0 Expla
13 min read
Smallest subarray with GCD as 1 | Segment Tree
Given an array arr[], the task is to find the smallest sub-arrays with GCD equal to 1. If there is no such sub-array then print -1. Examples: Input: arr[] = {2, 6, 3} Output: 3 {2, 6, 3} is the only sub-array with GCD = 1. Input: arr[] = {2, 2, 2} Output: -1 Approach: This problem can be solved in O(NlogN) using a segment-tree data structure. The s
10 min read
Number of subarrays with GCD = 1 | Segment tree
Given an array arr[], the task is to find the count of sub-arrays with GCD equal to 1.Examples: Input: arr[] = {1, 1, 1} Output: 6 Every single subarray of the given array has GCD of 1 and there are a total of 6 subarrays.Input: arr[] = {2, 2, 2} Output: 0 Approach: This problem can be solved in O(NlogN) using segment-tree data structure. The segme
10 min read
Queries for greatest pair sum in the given index range using Segment Tree
Given an array arr[] containing N integers and an array Q[] representing the range [L, R], the task is to find the greatest pair sum value in the range [L, R] where 0 ? L ? R ? N - 1. Examples: Input: arr[] = {1, 3, 2, 7, 9, 11}, Q[] = {1, 4} Output: 16 Explanation: The greatest pair sum in range 1 to 4 is 7 + 9 = 16. Input: arr[] = {0, 1, 2, 3, 4,
14 min read
Maximum of all subarrays of size K using Segment Tree
Given an array arr[] and an integer K, the task is to find the maximum for each and every contiguous subarray of size K. Examples: Input: arr[] = {1, 2, 3, 1, 4, 5, 2, 3, 6}, K = 3 Output: 3 3 4 5 5 5 6 Explanation: Maximum of 1, 2, 3 is 3 Maximum of 2, 3, 1 is 3 Maximum of 3, 1, 4 is 4 Maximum of 1, 4, 5 is 5 Maximum of 4, 5, 2 is 5 Maximum of 5,
14 min read
Maximum sum possible for every node by including it in a segment of N-Ary Tree
Given an N-Ary tree containing N nodes and an array weight [ ] that denotes the weight of the nodes which can be positive or negative, the task for every node is to print the maximum sum possible by a sequence of nodes including the current node. Examples: Input: N = 7 weight[] = [-8, 9, 7, -4, 5, -10, -6] N-Ary tree: -8 / \ 9 7 / \ / -4 5 -10 / -6
13 min read
Length of Longest Increasing Subsequences (LIS) using Segment Tree
Given an array arr[] of size N, the task is to count the number of longest increasing subsequences present in the given array. Example: Input: arr[] = {2, 2, 2, 2, 2}Output: 5Explanation: The length of the longest increasing subsequence is 1, i.e. {2}. Therefore, count of longest increasing subsequences of length 1 is 5. Input: arr[] = {1, 3, 5, 4,
15+ min read
Applications, Advantages and Disadvantages of Segment Tree
First, let us understand why we need it prior to landing on the introduction so as to get why this concept was introduced. Suppose we are given an array and we need to find out the subarray Purpose of Segment Trees: A segment tree is a data structure that deals with a range of queries over an array. It has a divide and conquers approach. Used to so
4 min read
Queries for the count of even digit sum elements in the given range using Segment Tree.
Given an array arr[] of N elements, the task is to answer Q queries each having two integers L and R. For each query, the task is to find the number of elements in the subarray arr[L...R] whose digit sum is even.Examples: Input: arr[] = {7, 3, 19, 13, 5, 4} query = { 1, 5 } Output: 3 Explanation: Elements 19, 13 and 4 have even digit sum in the sub
15+ min read
Queries for elements greater than K in the given index range using Segment Tree
Given an array arr[] of N elements and a number of queries where each query will contain three integers L, R, and K. For each query, the task is to find the number of elements in the subarray arr[L...R] which are greater than K. Examples: Input: arr[] = {7, 3, 9, 13, 5, 4}, q[] = {{0, 3, 6}, {1, 5, 8}} Output: 3 2 Query 1: Only 7, 9 and 13 are grea
15+ min read
Segment Tree | Sum of given range
Let us consider the following problem to understand Segment Trees.We have an array arr[0 . . . n-1]. We should be able to Find the sum of elements from index l to r where 0 &lt;= l &lt;= r &lt;= n-1Change the value of a specified element of the array to a new value x. We need to do arr[i] = x where 0 &lt;= i &lt;= n-1.Recommended PracticeSum of Que
15+ min read
Largest Rectangular Area in a Histogram using Segment Tree
Find the largest rectangular area possible in a given histogram where the largest rectangle can be made of a number of contiguous bars. For simplicity, assume that all bars have same width and the width is 1 unit. For example, consider the following histogram with 7 bars of heights {6, 2, 5, 4, 5, 1, 6}. The largest possible rectangle possible is 1
15+ min read
Segment Tree | Range Minimum Query
We have introduced segment tree with a simple example in the previous post. In this post, Range Minimum Query problem is discussed as another example where Segment Tree can be used. The following is the problem statement:We have an array arr[0 . . . n-1]. We should be able to efficiently find the minimum value from index qs (query start) to qe (que
15+ min read
Lazy Propagation in Segment Tree
Segment tree is introduced in previous post with an example of range sum problem. We have used the same "Sum of given Range" problem to explain Lazy propagation How does update work in Simple Segment Tree? In the previous post, update function was called to update only a single value in array. Please note that a single value update in array may cau
15+ min read
Persistent Segment Tree | Set 1 (Introduction)
Prerequisite : Segment Tree Persistency in Data Structure Segment Tree is itself a great data structure that comes into play in many cases. In this post we will introduce the concept of Persistency in this data structure. Persistency, simply means to retain the changes. But obviously, retaining the changes cause extra memory consumption and hence a
15+ min read
Article Tags :
three90RightbarBannerImg