Segment Tree - Range Minimum QueryIn the previous post, we described segment trees with a straightforward example. Another application of Segment Tree is explained in this post when it comes to the Range Minimum Query problem. The issue at hand is as follows: We have an array called arr[0, 1, n]. Where 0 = qs = qe = n-1, we should be able to efficiently identify the least value from index qs (query start) to qe (query end) 0 <= qs <= qe <= n-1. Finding the least element in the provided range by running a loop from qs to qe is a straightforward solution. In the worst situation, this solution takes O(n) time. Making a 2D array with an entry I j] that saves the smallest value in the range arr[i..j] is another option. Preprocessing takes O(n2) time, however it is now possible to find the minimum of a given range in O(1) time. Additionally, this method requires O(n2) additional space, which could be very expensive for big input arrays. Querying and preprocessing can be done quickly using segment trees. Preprocessing time with a segment tree is O(n), while a range minimum query has an O time complexity (Logn). The additional storage needed for the segment tree is O(n). Segment tree representation
Segment Trees are shown as an array representation of a tree. The left child of each node at index I is at index 2*i+1, the right child is at index 2*i+2, and the parent is at index( I - 1) / 2. Building a segment tree from an arrayWe begin by examining the segment arr[0,... n-1]. the current segment is split in half each time (assuming it hasn't already become a segment of length 1), the identical operation is then run on both halves, and we store the minimum value for each such segment in a segment tree node. Except for the last level, every level of the created segment tree will be fully filled. Additionally, since we consistently split segments into two halves at every level, the tree will be a full binary tree. There will be n-1 internal nodes because the created tree is always a full binary tree with n leaves. Consequently, there will be 2*n - 1 nodes overall. The segment tree will be log2n in height. Given that the tree is represented using an array and that the relationship between parent and child indexes must be preserved, 2 * 2 log2n - 1 of memory will be allocated for the segment tree. Find the least value of the specified range.How to perform a range minimum query utilising the segment tree once it has been built. The algorithm to find the minimum is as follows. C++ CodeThe application of the aforementioned strategy is seen below: Output: Minimum of values in range [1, 5] is = 2
Next TopicSegment Tree - Sum of given Range |
We provides tutorials and interview questions of all technology like java tutorial, android, java frameworks
G-13, 2nd Floor, Sec-3, Noida, UP, 201301, India