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
1 Find the minimum of elements from index l to r where 0 <= l <= r <= 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 <= i <= n-1.
Input : 2, 6, 7, 5, 18, 86, 54, 2 minimum(2, 7) update(3, 4) minimum(2, 6) Output : Minimum in range 2 to 7 is 2. Minimum in range 2 to 6 is 4.
The iterative version of the segment tree basically uses the fact, that for an index i, left child = 2 * i and right child = 2 * i + 1 in the tree. The parent for an index i in the segment tree array can be found by parent = i / 2. Thus we can easily travel up and down through the levels of the tree one by one. At first we compute the minimum in the ranges while constructing the tree starting from the leaf nodes and climbing up through the levels one by one. We use the same concept while processing the queries for finding the minimum in a range. Since there are (log n) levels in the worst case, so querying takes log n time. For update of a particular index to a given value we start updating the segment tree starting from the leaf nodes and update all those nodes which are affected by the updation of the current node by gradually moving up through the levels at every iteration. Updation also takes log n time because there we have to update all the levels starting from the leaf node where we update the exact value at the exact index given by the user.
Minimum in range 0 to 5 is 2 Minimum in range 2 to 6 is 1
Time Complexity(n log n)
Auxiliary Space (n)
- Iterative Segment Tree (Range Maximum Query with Node Update)
- Segment Tree | Set 2 (Range Minimum Query)
- Segment Tree | Set 2 (Range Maximum Query with Node Update)
- Segment Tree | Set 1 (Sum of given range)
- Segment Tree | Set 3 (XOR of given range)
- Segment Tree | (XOR of a given range )
- Range Minimum Query (Square Root Decomposition and Sparse Table)
- Overview of Data Structures | Set 3 (Graph, Trie, Segment Tree and Suffix Tree)
- Range query for count of set bits
- Range sum query using Sparse Table
- Segment Trees | (Product of given Range Modulo m)
- Range query for Largest Sum Contiguous Subarray
- Difference Array | Range update query in O(1)
- Range and Update Query for Chessboard Pieces
- LIS using Segment Tree
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.