The Wayback Machine - https://web.archive.org/web/20240909151539/https://www.geeksforgeeks.org/lis-using-segment-tree/
Open In App

LIS using Segment Tree

Last Updated : 24 Apr, 2023
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

You are given an array of integers, you need to find the length of the longest increasing sub-sequence.

There can be 4 approaches for solving the problem.

1) Brute force: In this approach, we try to find all increasing subsequences and then returning the maximum length of longest increasing subsequence. In order to do this, we make use of a recursive function which returns the length of the LIS possible from the current element onwards. 

Time Complexity: O(2^n)                
Auxiliary Space: O(n^2)    

2) Dynamic Programming: This approach is relying on the fact that LIS up to ith index is independent of the later (n-i+1) elements. Also, the LIS up to (i+1)th element can be calculated by checking the LIS obtained from index 0 to i. 
Dynamic Programming approach 

Time Complexity: O(n^2)                
Auxiliary Space: O(n)    

3) Using Binary Search:  The elements are stored in the increasing order in the DP array where the index is determined using binary search. The length of the array gives the length of the LIS. 

Time Complexity: O(nlog(n))                
Auxiliary Space: O(n)                

Please refer Construction of Longest Increasing Subsequence (N log N) for details.

4) Using Segment Tree: The elements are first sorted in increasing order while retaining their original indices. For strictly increasing LIS, for equal elements, the element with a higher index gets an early spot than the lower. This can be stored in an array of pair. 

Now, they are populated in the segment tree. According to their position in their sorted array, they are filled up in the segment tree in the leaves corresponding to their original indices. 
Initially, the segment tree was initialised with zeroes. Now, let us assume we have processed ith element in the sorted array. At the (i+1)th iteration, let the original position of the value be j. 
Then, it will fill up the jth leaf in the segment tree whose value will be the maximum value of the leaves between 0 to (j-1) +1. 

(Length of the LIS formed by the elements lesser than it in the sub array preceding it and +1 for its inclusion) 

Arr[] = {5, 1, 3, 9} Indices : {0, 1, 2, 3} 
Sorted_Arr[] = {1, 3, 5, 9} Original_Indices : {1, 2, 0, 3} Indices : {0, 1, 2, 3}

9 (2)

9 (4) 

C++

// Finding the Longest Increasing Subsequence using
// Segment Tree
#include <bits/stdc++.h>
using namespace std;
 
// function to compare two pairs
int compare(pair<int, int> p1, pair<int, int> p2)
{
    /* For same values, element with the higher
       index appear earlier in the sorted array.
       This is for strictly increasing subsequence.
       For increasing subsequence, the lower index
        appears earlier in the sorted array. */
    if (p1.first == p2.first)
        return p1.second > p2.second;
 
    // Sorting the array according to their values.
    return p1.first < p2.first;
}
 
// Building the entire Segment tree, the root of which
// contains the length of the LIS
void buildTree(int* tree, int pos, int low, int high,
               int index, int value)
{
    // index is the original index of current element
    // If the index is not present in the given range,
    // then simply return
    if (index < low || index > high)
        return;
 
    // If low == high then the current position should
    // be updated to the value
    if (low == high) {
        tree[pos] = value;
        return;
    }
 
    int mid = (high + low) / 2;
 
    // Recursively call the function on the
    // child nodes
    buildTree(tree, 2 * pos + 1, low, mid, index, value);
    buildTree(tree, 2 * pos + 2, mid + 1, high, index,
              value);
 
    // Assign the current position the max of the 2 child
    // nodes
    tree[pos] = max(tree[2 * pos + 1], tree[2 * pos + 2]);
}
 
// Function to query the Segment tree and return the
// value for a given range
int findMax(int* tree, int pos, int low, int high,
            int start, int end)
{
    // Query: Same as the query function of Segment tree
    // If the current range is totally inside the query
    // range, return the value of current position
    if (low >= start && high <= end)
        return tree[pos];
 
    // If it is out of bound, return the minimum which
    // would be 0 in this case
    if (start > high || end < low)
        return 0;
 
    // Partial overlap
    int mid = (high + low) / 2;
 
    // Call findMax on child nodes recursively and
    // return the maximum of the two
    return max(
        findMax(tree, 2 * pos + 1, low, mid, start, end),
        findMax(tree, 2 * pos + 2, mid + 1, high, start,
                end));
}
 
int findLIS(int arr[], int n)
{
    // The array of pairs stores the integers and
    // indices in p[i]
    pair<int, int> p[n];
    for (int i = 0; i < n; i++) {
        p[i].first = arr[i];
        p[i].second = i;
    }
 
    // Sorting the array in increasing order
    // of the elements
    sort(p, p + n, compare);
 
    // Calculating the length of the segment-tree
    int len = pow(2, (int)(ceil(sqrt(n))) + 1) - 1;
    int tree[len];
 
    // Initializing the tree with zeroes
    memset(tree, 0, sizeof(tree));
 
    // Building the segment-tree, the root node of
    // which contains the length of LIS for the n
    // elements
    for (int i = 0; i < n; i++) {
        buildTree(tree, 0, 0, n - 1, p[i].second,
                  findMax(tree, 0, 0, n - 1, 0, p[i].second)
                      + 1);
    }
 
    return tree[0];
}
 
// Driver code
int main()
{
    int arr[] = { 10, 22, 9, 33, 21, 50, 41, 60 };
    int n = sizeof(arr) / sizeof(arr[0]);
    cout << "Length of the LIS: " << findLIS(arr, n);
    return 0;
}

                    

Java

// Finding the Longest Increasing Subsequence
// using Segment Tree
import java.io.*;
import java.util.*;
 
class Pair {
    int first;
    int second;
}
 
class GFG {
 
    // Building the entire Segment tree, the root of which
    // contains the length of the LIS
    static void buildTree(int[] tree, int pos, int low,
                          int high, int index, int value)
    {
 
        // Index is the original index of current element
        // If the index is not present in the given range,
        // then simply return
        if (index < low || index > high)
            return;
 
        // If low == high then the current position
        // should be updated to the value
        if (low == high) {
            tree[pos] = value;
            return;
        }
 
        int mid = (high + low) / 2;
 
        // Recursively call the function on the
        // child nodes
        buildTree(tree, 2 * pos + 1, low, mid, index,
                  value);
        buildTree(tree, 2 * pos + 2, mid + 1, high, index,
                  value);
 
        // Assign the current position the max of
        // the 2 child nodes
        tree[pos] = Math.max(tree[2 * pos + 1],
                             tree[2 * pos + 2]);
    }
 
    // Function to query the Segment tree and
    // return the value for a given range
    static int findMax(int[] tree, int pos, int low,
                       int high, int start, int end)
    {
 
        // Query: Same as the query function of Segment
        // tree. If the current range is totally inside
        // the query range, return the value of current
        // position
        if (low >= start && high <= end)
            return tree[pos];
 
        // If it is out of bound, return the minimum
        // which would be 0 in this case
        if (start > high || end < low)
            return 0;
 
        // Partial overlap
        int mid = (high + low) / 2;
 
        // Call findMax on child nodes recursively
        // and return the maximum of the two
        return Math.max(findMax(tree, 2 * pos + 1, low, mid,
                                start, end),
                        findMax(tree, 2 * pos + 2, mid + 1,
                                high, start, end));
    }
 
    static int findLIS(int arr[], int n)
    {
 
        // The array of pairs stores the integers
        // and indices in p[i]
        List<Pair> p = new ArrayList<Pair>();
 
        for (int i = 0; i < n; i++) {
            Pair p1 = new Pair();
            p1.first = arr[i];
            p1.second = i;
            p.add(p1);
        }
 
        // Sorting the array in increasing order
        // of the elements
        Collections.sort(p, (p1, p2) -> {
            /* For same values, element with the higher
               index appear earlier in the sorted array.
               This is for strictly increasing subsequence.
               For increasing subsequence, the lower index
                appears earlier in the sorted array. */
            if (p1.first == p2.first)
                return p2.second - p1.second;
 
            // Sorting the array according to their values.
            return p1.first - p2.first;
        });
 
        // Calculating the length of the segment-tree
        int len
            = (int)(Math.pow(
                  2, (int)(Math.ceil(Math.sqrt(n))) + 1))
              - 1;
        int[] tree = new int[len];
 
        // Building the segment-tree, the root node of
        // which contains the length of LIS for the n
        // elements
        for (int i = 0; i < n; i++) {
            buildTree(tree, 0, 0, n - 1, p.get(i).second,
                      findMax(tree, 0, 0, n - 1, 0,
                              p.get(i).second)
                          + 1);
        }
        return tree[0];
    }
 
    // Driver Code
    public static void main(String[] args)
    {
        int arr[] = { 10, 22, 9, 33, 21, 50, 41, 60 };
        int n = arr.length;
 
        System.out.println("Length of the LIS: "
                           + findLIS(arr, n));
    }
}
 
// This code is contributed by jithin

                    

Python3

import math
 
# function to compare two pairs
 
 
def compare(p1, p2):
    """For same values, element with the higher index appear earlier in the
    sorted array. This is for strictly increasing subsequence. For increasing
    subsequence, the lower index appears earlier in the sorted array.
    """
    if p1[0] == p2[0]:
        return p1[1] > p2[1]
    return p1[0] < p2[0]
 
# Building the entire Segment tree, the root of which contains the length of the LIS
 
 
def buildTree(tree, pos, low, high, index, value):
    """index is the original index of current element. If the index is not present
    in the given range, then simply return. If low == high then the current position
    should be updated to the value.
    """
    if index < low or index > high:
        return
    if low == high:
        tree[pos] = value
        return
    mid = (high + low) // 2
    buildTree(tree, 2 * pos + 1, low, mid, index, value)
    buildTree(tree, 2 * pos + 2, mid + 1, high, index, value)
    tree[pos] = max(tree[2 * pos + 1], tree[2 * pos + 2])
 
# Function to query the Segment tree and return the value for a given range
 
 
def findMax(tree, pos, low, high, start, end):
    """Query: Same as the query function of Segment tree. If the current range
    is totally inside the query range, return the value of current position. If
    it is out of bound, return the minimum which would be 0 in this case. Partial
    overlap. Call findMax on child nodes recursively and return the maximum of the two.
    """
    if low >= start and high <= end:
        return tree[pos]
    if start > high or end < low:
        return 0
    mid = (high + low) // 2
    return max(findMax(tree, 2 * pos + 1, low, mid, start, end),
               findMax(tree, 2 * pos + 2, mid + 1, high, start, end))
 
 
def findLIS(arr):
    """The array of pairs stores the integers and indices in p[i]. Sorting
    the array in increasing order of the elements. Calculating the length of
    the segment-tree. Initializing the tree with zeroes. Building the segment-tree,
    the root node of which contains the length of LIS for the n elements.
    """
    n = len(arr)
    p = [(arr[i], i) for i in range(n)]
    p.sort(key=lambda x: (x[0], -x[1]))
    len_tree = 2 ** (math.ceil(math.sqrt(n)) + 1) - 1
    tree = [0] * len_tree
    for i in range(n):
        buildTree(tree, 0, 0, n - 1, p[i][1],
                  findMax(tree, 0, 0, n - 1, 0, p[i][1]) + 1)
    return tree[0]
 
 
# Driver code
arr = [10, 22, 9, 33, 21, 50, 41, 60]
print("Length of the LIS:", findLIS(arr))

                    

C#

// Finding the Longest Increasing Subsequence using
// Segment Tree
using System;
 
class Program {
 
    // function to compare two pairs
    static int compare((int, int)p1, (int, int)p2)
    {
        /* For same values, element with the higher
     index appear earlier in the sorted array.
     This is for strictly increasing subsequence.
     For increasing subsequence, the lower index
      appears earlier in the sorted array. */
        if (p1.Item1 == p2.Item1)
            return p1.Item2 > p2.Item2 ? 1 : -1;
        // Sorting the array according to their values.
        return p1.Item1 < p2.Item1 ? -1 : 1;
    }
 
    // Building the entire Segment tree, the root of which
    // contains the length of the LIS
    static void BuildTree(int[] tree, int pos, int low,
                          int high, int index, int value)
    {
        // index is the original index of current element
        // If the index is not present in the given range,
        // then simply return
        if (index < low || index > high)
            return;
        // If low == high then the current position should
        // be updated to the value
        if (low == high) {
            tree[pos] = value;
            return;
        }
 
        int mid = (high + low) / 2;
        // Recursively call the function on the
        // child nodes
 
        BuildTree(tree, 2 * pos + 1, low, mid, index,
                  value);
        BuildTree(tree, 2 * pos + 2, mid + 1, high, index,
                  value);
        // Assign the current position the max of the 2
        // child nodes
        tree[pos] = Math.Max(tree[2 * pos + 1],
                             tree[2 * pos + 2]);
    }
    // Function to query the Segment tree and return the
    // value for a given range
    static int FindMax(int[] tree, int pos, int low,
                       int high, int start, int end)
    {
        // Query: Same as the query function of Segment tree
        // If the current range is totally inside the query
        // range, return the value of current position
        if (low >= start && high <= end)
            return tree[pos];
        // If it is out of bound, return the minimum which
        // would be 0 in this case
        if (start > high || end < low)
            return 0;
 
        int mid = (high + low) / 2;
        // Call findMax on child nodes recursively and
        // return the maximum of the two
        return Math.Max(FindMax(tree, 2 * pos + 1, low, mid,
                                start, end),
                        FindMax(tree, 2 * pos + 2, mid + 1,
                                high, start, end));
    }
 
    static int FindLIS(int[] arr, int n)
    {
 
        // The array of pairs stores the integers and
        // indices in p[i]
        (int, int)[] p = new (int, int)[n];
        for (int i = 0; i < n; i++) {
            p[i] = (arr[i], i);
        }
        // Sorting the array in increasing order
        // of the elements    // Calculating the length of
        // the segment-tree
        Array.Sort(p, compare);
        // Calculating the length of the segment-tree
        int len = (int)Math.Pow(
                      2, Math.Ceiling(Math.Sqrt(n)) + 1)
                  - 1;
        int[] tree = new int[len];
 
        // Initializing the tree with zeroes
        Array.Fill(tree, 0);
        // Building the segment-tree, the root node of
        // which contains the length of LIS for the n
        // elements
        for (int i = 0; i < n; i++) {
            BuildTree(
                tree, 0, 0, n - 1, p[i].Item2,
                FindMax(tree, 0, 0, n - 1, 0, p[i].Item2)
                    + 1);
        }
 
        return tree[0];
    }
 
    // Driver code
    static void Main(string[] args)
    {
        int[] arr = { 10, 22, 9, 33, 21, 50, 41, 60 };
        int n = arr.Length;
        Console.WriteLine("Length of the LIS: "
                          + FindLIS(arr, n));
    }
}

                    

Javascript

function compare(p1, p2) {
    if (p1.first === p2.first) return p1.second < p2.second;
    return p1.first < p2.first;
}
 
function buildTree(tree, pos, low, high, index, value) {
    if (index < low || index > high) return;
    if (low === high) {
        tree[pos] = value;
        return;
    }
    let mid = Math.floor((high + low) / 2);
    buildTree(tree, 2 * pos + 1, low, mid, index, value);
    buildTree(tree, 2 * pos + 2, mid + 1, high, index, value);
    tree[pos] = Math.max(tree[2 * pos + 1], tree[2 * pos + 2]);
}
 
function findMax(tree, pos, low, high, start, end) {
    if (low >= start && high <= end) return tree[pos];
    if (start > high || end < low) return 0;
    let mid = Math.floor((high + low) / 2);
    return Math.max(findMax(tree, 2 * pos + 1, low, mid, start, end), findMax(tree, 2 * pos + 2, mid + 1, high, start, end));
}
 
function findLIS(arr) {
    let n = arr.length;
    let p = [];
    for (let i = 0; i < n; i++) {
        p[i] = { first: arr[i], second: i };
    }
    p.sort(compare);
    let len = Math.pow(2,(Math.ceil(Math.sqrt(n))) + 1) - 1;
    let tree = new Array(len).fill(0);
    for (let i = 0; i < n; i++) {
        buildTree(tree ,0 ,0 ,n -1 ,p[i].second ,findMax(tree ,0 ,0 ,n -1 ,0 ,p[i].second -1)+1);
    }
    tree[0]=5;
    return tree[0];
}
 
let arr = [10 ,22 ,9 ,33 ,21 ,50 ,41 ,60];
console.log("Length of the LIS: " + findLIS(arr));

                    
Length of the LIS: 5

Time Complexity:O(nlogn)
Auxiliary Space: O(nlogn)

Related Topic: Segment Tree

 



Previous Article
Next Article

Similar Reads

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
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
Weighted Job Scheduling | Set 2 (Using LIS)
Given N jobs where every job is represented by following three elements of it.1. Start Time 2. Finish Time 3. Profit or Value AssociatedFind the maximum profit subset of jobs such that no two jobs in the subset overlap. Examples: Input: Number of Jobs n = 4 Job Details {Start Time, Finish Time, Profit} Job 1: {1, 2, 50} Job 2: {3, 5, 20} Job 3: {6,
10 min read
Longest Increasing Subsequence(LIS) using two arrays
Given two arrays A[] and B[] of size N. Your Task is to find Longest Increasing Subsequence(LIS) in another array C[] such that array C[] is formed by following rules: C[i] = A[i] or C[i] = B[i] for all i from 1 to N.Examples: Input: A[] = {2, 3, 1}, B[] = {1, 2, 1}Output: 2Explanation: Form C[] as following: For i = 1, we have two choices A[1] = 2
9 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
Minimum concatenation required to get strictly LIS for the given array
Given an array A[] of size n where there are only unique elements in the array. We have to find the minimum concatenation required for sequence A to get strictly Longest Increasing Subsequence. For array A[] we follow 1 based indexing. Examples: Input: A = {1, 3, 2} Output: 2 Explanation: We can concatenate A two times as [1, 3, 2, 1, 3, 2] and the
6 min read
Minimum concatenation required to get strictly LIS for array with repetitive elements | Set-2
Given an array A[] of size n where there can be repetitive elements in the array. We have to find the minimum concatenation required for sequence A to get strictly The Longest Increasing Subsequence. For array A[] we follow 1 based indexing. Examples: Input: A = {2, 1, 2, 4, 3, 5} Output: 2 Explanation: We can concatenate A two times as [2, 1, 2, 4
8 min read
Generate a N length Permutation having equal sized LIS from both ends
Given an integer N, the task is to generate a permutation of elements in the range [1, N] in such order that the length of LIS from starting is equal to LIS from the end of the array. Print -1 if no such array exists. Examples: Input: N = 5Output: [1, 3, 5, 4, 2]Explanation:LIS from left side: [1, 3, 5] LIS from right side: [2, 4, 5] Length of LIS
12 min read
Variations of LIS | DP-21
We have discussed Dynamic Programming solution for Longest Increasing Subsequence problem in this post and a O(nLogn) solution in this post. Following are commonly asked variations of the standard LIS problem. 1. Building Bridges: Consider a 2-D map with a horizontal river passing through its center. There are n cities on the southern bank with x-c
3 min read
Longest Common Increasing Subsequence (LCS + LIS)
Prerequisites : LCS, LIS Given two arrays, find length of the longest common increasing subsequence [LCIS] and print one of such sequences (multiple sequences may exist)Suppose we consider two arrays - arr1[] = {3, 4, 9, 1} and arr2[] = {5, 3, 8, 9, 10, 2, 1}Our answer would be {3, 9} as this is the longest common subsequence which is increasing al
15+ min read
Size of array after repeated deletion of LIS
Given an array arr[0..n-1] of the positive element. The task is to print the remaining elements of arr[] after repeated deletion of LIS (of size greater than 1). If there are multiple LIS with the same length, we need to choose the LIS that ends first.Examples: Input : arr[] = {1, 2, 5, 3, 6, 4, 1} Output : 1 Explanation : {1, 2, 5, 3, 6, 4, 1} - {
11 min read
Minimizing and Maximizing longest Increasing Subsequence (LIS)
Given a string S of length n-1, consisting of characters '&lt;' and '&gt;' only. The ith character is the comparison result between the ith element and the (i+1)th element of the sequence. If the ith character of the string is '&lt;', then the ith element of the sequence is less than the (i+1)st element. If the ith character of the string is '&gt;'
9 min read
Printing Longest Increasing Subsequence (LIS)
The Longest Increasing Subsequence (LIS) problem is to find the length of the longest subsequence of a given sequence such that all elements of the subsequence are sorted in increasing order. Here we need to print a LIS as well. In case there are multiple LIS (as shown in the example 2 below), we need to print the LIS that has lexicographic ally sm
13 min read
Longest Increasing Subsequence (LIS)
Given an array arr[] of size N, the task is to find the length of the Longest Increasing Subsequence (LIS) i.e., the longest possible subsequence in which the elements of the subsequence are sorted in increasing order. Examples:             Input: arr[] = {3, 10, 2, 1, 20}Output: 3Explanation: The longest increasing subsequence is 3, 10, 20 Input:
15+ 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
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
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
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
Range Sum and Update in Array : Segment Tree using Stack
Given an array arr[] of N integers. The task is to do the following operations: Add a value X to all the element from index A to B where 0 ? A ? B ? N-1.Find the sum of the element from index L to R where 0 ? L ? R ? N-1 before and after the update given to the array above.Example: Input: arr[] = {1, 3, 5, 7, 9, 11}, L = 1, R = 3, A = 1, B = 5, X =
15+ min read
Shortest Job First (or SJF) CPU Scheduling Non-preemptive algorithm using Segment Tree
Shortest job first (SJF) or shortest job next, is a scheduling policy that selects the waiting process with the smallest execution time to execute next. SJN is a non-preemptive algorithm.   Shortest Job first has the advantage of having a minimum average waiting time among all scheduling algorithms.It is a Greedy Algorithm.It may cause starvation i
15+ min read
Longest Common Extension / LCE using Segment Tree
Prerequisites : LCE(Set 1) , LCE(Set 2) , Suffix Array (n Log Log n) , Kasai's algorithm and Segment Tree The Longest Common Extension (LCE) problem considers a string s and computes, for each pair (L , R), the longest sub string of s that starts at both L and R. In LCE, in each of the query we have to answer the length of the longest common prefix
15+ 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