Segment Tree | Set 2 (Range Minimum Query) | GeeksforGeeks
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 (query end) where 0 <= qs <= qe <= n-1. The array is static (elements are not deleted and inserted during the series of queries).
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 (query end) where 0 <= qs <= qe <= n-1. The array is static (elements are not deleted and inserted during the series of queries).
Another solution is to create a 2D array where an entry [i, j] stores the minimum value in range arr[i..j]. Minimum of a given range can now be calculated in O(1) time, but preprocessing takes O(n^2) time. Also, this approach needs O(n^2) extra space which may become huge for large input arrays.
Segment tree can be used to do preprocessing and query in moderate time. With segment tree, preprocessing time is O(n) and time to for range minimum query is O(Logn). The extra space required is O(n) to store the segment tree.
Representation of Segment trees
1. Leaf Nodes are the elements of the input array.
2. Each internal node represents minimum of all leaves under it.
1. Leaf Nodes are the elements of the input array.
2. Each internal node represents minimum of all leaves under it.
An array representation of tree is used to represent Segment Trees. For each node at index i, the left child is at index 2*i+1, right child at 2*i+2 and the parent is at .
Time Complexity for tree construction is O(n). Ther are total 2n-1 nodes, and value of every node is calculated only once in tree construction.
Time complexity to query is O(Logn). To query a range minimum, we process at most two nodes at every level and number of levels is O(Logn).
Query for minimum value of given range
Once the tree is constructed, how to do range minimum query using the constructed segment tree. Following is algorithm to get the minimum.
Once the tree is constructed, how to do range minimum query using the constructed segment tree. Following is algorithm to get the minimum.
// qs --> query start index, qe --> query end index int RMQ(node, qs, qe) { if range of node is within qs and qe return value in node else if range of node is completely outside qs and qe return INFINITE else return min( RMQ(node's left child, qs, qe), RMQ(node's right child, qs, qe) ) }
class
SegmentTreeRMQ
{
int
st[];
//array to store segment tree
// A utility function to get minimum of two numbers
int
minVal(
int
x,
int
y) {
return
(x < y) ? x : y;
}
// A utility function to get the middle index from corner
// indexes.
int
getMid(
int
s,
int
e) {
return
s + (e - s) /
2
;
}
/* A recursive function to get the minimum value in a given
range of array indexes. The following are parameters for
this function.
st --> Pointer to segment tree
index --> Index of current node in the segment tree. Initially
0 is passed as root is always at index 0
ss & se --> Starting and ending indexes of the segment
represented by current node, i.e., st[index]
qs & qe --> Starting and ending indexes of query range */
int
RMQUtil(
int
ss,
int
se,
int
qs,
int
qe,
int
index)
{
// If segment of this node is a part of given range, then
// return the min of the segment
if
(qs <= ss && qe >= se)
return
st[index];
// If segment of this node is outside the given range
if
(se < qs || ss > qe)
return
Integer.MAX_VALUE;
// If a part of this segment overlaps with the given range
int
mid = getMid(ss, se);
return
minVal(RMQUtil(ss, mid, qs, qe,
2
* index +
1
),
RMQUtil(mid +
1
, se, qs, qe,
2
* index +
2
));
}
// Return minimum of elements in range from index qs (quey
// start) to qe (query end). It mainly uses RMQUtil()
int
RMQ(
int
n,
int
qs,
int
qe)
{
// Check for erroneous input values
if
(qs <
0
|| qe > n -
1
|| qs > qe) {
System.out.println(
"Invalid Input"
);
return
-
1
;
}
return
RMQUtil(
0
, n -
1
, qs, qe,
0
);
}
// A recursive function that constructs Segment Tree for
// array[ss..se]. si is index of current node in segment tree st
int
constructSTUtil(
int
arr[],
int
ss,
int
se,
int
si)
{
// If there is one element in array, store it in current
// node of segment tree and return
if
(ss == se) {
st[si] = arr[ss];
return
arr[ss];
}
// If there are more than one elements, then recur for left and
// right subtrees and store the minimum of two values in this node
int
mid = getMid(ss, se);
st[si] = minVal(constructSTUtil(arr, ss, mid, si *
2
+
1
),
constructSTUtil(arr, mid +
1
, se, si *
2
+
2
));
return
st[si];
}
/* Function to construct segment tree from given array. This function
allocates memory for segment tree and calls constructSTUtil() to
fill the allocated memory */
void
constructST(
int
arr[],
int
n)
{
// Allocate memory for segment tree
//Height of segment tree
int
x = (
int
) (Math.ceil(Math.log(n) / Math.log(
2
)));
//Maximum size of segment tree
int
max_size =
2
* (
int
) Math.pow(
2
, x) -
1
;
st =
new
int
[max_size];
// allocate memory
// Fill the allocated memory st
constructSTUtil(arr,
0
, n -
1
,
0
);
}
Lintcode: https://codesolutiony.wordpress.com/2015/05/12/lintcode-interval-minimum-number/
Given an integer array (index from 0 to n-1, where n is the size of this array), and an query list. Each query has two integers [start, end]. For each query, calculate the minimum number between index start and end in the given array, return the result list. Have you met this question in a real interview? Yes Example For array [1,2,7,8,5], and queries [(1,2),(0,4),(2,4)], return [2,1,5] Note We suggest you finish problem Segment Tree Build, Segment Tree Query and Segment Tree Modify first. Challenge O(logN) time for each query
public ArrayList<Integer> intervalMinNumber(int[] A,
ArrayList<Interval> queries) {
ArrayList<Integer> res = new ArrayList<Integer>();
if (A == null || A.length == 0 || queries == null || queries.size() == 0) {
return res;
}
MinTreeNode root = buildTree(A, 0, A.length - 1);
for (Interval interval : queries) {
res.add(getVal(root, interval.start, interval.end));
}
return res;
}
private int getVal(MinTreeNode root, int from, int to) {
if (root == null || root.end < from || root.start > to) {
return Integer.MAX_VALUE;
}
if (root.start == root.end || (from <= root.start && to >= root.end)) {
return root.min;
}
return Math.min(getVal(root.left, from, to), getVal(root.right, from, to));
}
private MinTreeNode buildTree(int[] A, int from, int to) {
if (from > to) {
return null;
}
if (from == to) {
return new MinTreeNode(from, from, A[from]);
}
MinTreeNode root = new MinTreeNode(from, to);
root.left = buildTree(A, from, (from + to) / 2);
root.right = buildTree(A, (from + to) / 2 + 1, to);
if (root.left == null) {
root.min = root.right.min;
} else if (root.right == null) {
root.min = root.left.min;
} else {
root.min = Math.min(root.left.min, root.right.min);
}
return root;
}
class MinTreeNode {
int start;
int end;
int min;
MinTreeNode left;
MinTreeNode right;
public MinTreeNode(int start, int end) {
this.start = start;
this.end = end;
}
public MinTreeNode(int start, int end, int min) {
this(start, end);
this.min = min;
}
}
public
class
RMQTree {
int
[] data;
int
[] tree;
int
nextPowerOf2(
int
n ){
int
p =
1
;
for
( ; p < n; p <<=
1
);
return
p;
}
void
init(
int
root,
int
f,
int
t ){
if
( f == t ){
tree[root] = f;
}
else
{
int
m = (f+t)/
2
, l = left(root), r = right(root);
init( l, f, m );
init( r, m+
1
, t );
tree[root] = ( data[tree[l]] < data[tree[r]] ) ? tree[l] : tree[r];
}
}
RMQTree(
int
[] a ){
data = a;
int
n = a.length;
int
p = nextPowerOf2( n );
tree =
new
int
[
2
*p-
1
];
init(
0
,
0
, n-
1
);
}
int
parent(
int
i ){
return
(i-
1
)/
2
;
}
int
left(
int
i ){
return
2
*i+
1
;
}
int
right(
int
i ){
return
2
*i+
2
;
}
int
minimum(
int
root,
int
low,
int
high,
int
f,
int
t ){
// return
// the index of the minimal value of the array within the range a[f, ..., t],
// provided the portion of the array within the range a[low,...,high]
if
( t < low || high < f )
return
-
1
;
if
( f <= low && high <= t )
return
tree[root];
int
l = left(root);
int
r = right(root);
int
m = (low+high)/
2
;
int
l_min = minimum(l, low, m, f, t );
int
r_min = minimum(r, m+
1
, high, f, t );
if
( l_min==-
1
)
return
r_min;
if
( r_min==-
1
)
return
l_min;
return
data[l_min] < data[r_min] ? l_min : r_min;
}
int
minimum(
int
f,
int
t ){
return
minimum(
0
,
0
, data.length-
1
, f, t );
}
}
Range Sum:
int
query(
int
l,
int
r)
{
int
ans = 0;
for
(l += n, r+=n; l < r; l >>= 1, r >>= 1)
ans = ((l&1) ? t[l++] : 0) + ((r&1) ? t[--r] : 0);
return
ans;
}
Another solution is to create a 2D array where an entry [i, j] stores the minimum value in range arr[i..j]. Minimum of a given range can now be calculated in O(1) time, but preprocessing takes O(n^2) time. Also, this approach needs O(n^2) extra space which may become huge for large input arrays.
Read full article from Segment Tree | Set 2 (Range Minimum Query) | GeeksforGeeks