The Wayback Machine - https://web.archive.org/web/20240815035837/https://www.geeksforgeeks.org/construction-of-longest-monotonically-increasing-subsequence-n-log-n/
Open In App

Construction of Longest Increasing Subsequence (N log N)

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

In my previous post, I have explained about longest increasing sub-sequence (LIS) problem in detail. However, the post only covered code related to querying size of LIS, but not the construction of LIS. I left it as an exercise. If you have solved, cheers. If not, you are not alone, here is code.

If you have not read my previous post, read here. Note that the below code prints LIS in reverse order. We can modify print order using a stack (explicit or system stack). I am leaving explanation as an exercise (easy). 

C++




// C++ implementation to find longest increasing subsequence
// in O(n Log n) time.
#include <bits/stdc++.h>
using namespace std;
 
// Binary search
int GetCeilIndex(int arr[], vector<int>& T, int l, int r,
                 int key)
{
    while (r - l > 1) {
        int m = l + (r - l) / 2;
        if (arr[T[m]] >= key)
            r = m;
        else
            l = m;
    }
 
    return r;
}
 
int LongestIncreasingSubsequence(int arr[], int n)
{
    // Add boundary case, when array n is zero
    // Depend on smart pointers
 
    vector<int> tailIndices(n, 0); // Initialized with 0
    vector<int> prevIndices(n, -1); // initialized with -1
 
    int len = 1; // it will always point to empty location
    for (int i = 1; i < n; i++) {
        if (arr[i] < arr[tailIndices[0]]) {
            // new smallest value
            tailIndices[0] = i;
        }
        else if (arr[i] > arr[tailIndices[len - 1]]) {
            // arr[i] wants to extend largest subsequence
            prevIndices[i] = tailIndices[len - 1];
            tailIndices[len++] = i;
        }
        else {
            // arr[i] wants to be a potential condidate of
            // future subsequence
            // It will replace ceil value in tailIndices
            int pos = GetCeilIndex(arr, tailIndices, -1,
                                   len - 1, arr[i]);
 
            prevIndices[i] = tailIndices[pos - 1];
            tailIndices[pos] = i;
        }
    }
 
    cout << "LIS of given input" << endl;
    for (int i = tailIndices[len - 1]; i >= 0; i = prevIndices[i])
        cout << arr[i] << " ";
    cout << endl;
 
    return len;
}
 
int main()
{
    int arr[] = { 2, 5, 3, 7, 11, 8, 10, 13, 6 };
    int n = sizeof(arr) / sizeof(arr[0]);
 
    printf("LIS size %d\n", LongestIncreasingSubsequence(arr, n));
 
    return 0;
}


Java




// Java implementation to find longest
// increasing subsequence in O(n Log n)
// time.
import java.util.Arrays;
 
class GFG {
 
    // Binary search
    static int GetCeilIndex(int arr[],
                            int T[], int l,
                            int r, int key)
    {
 
        while (r - l > 1) {
 
            int m = l + (r - l) / 2;
            if (arr[T[m]] >= key)
                r = m;
            else
                l = m;
        }
 
        return r;
    }
 
    static int LongestIncreasingSubsequence(
        int arr[], int n)
    {
 
        // Add boundary case, when array n is zero
        // Depend on smart pointers
 
        int tailIndices[] = new int[n];
 
        // Initialized with 0
        Arrays.fill(tailIndices, 0);
 
        int prevIndices[] = new int[n];
 
        // initialized with -1
        Arrays.fill(prevIndices, -1);
 
        // it will always point to empty
        // location
        int len = 1;
 
        for (int i = 1; i < n; i++) {
            if (arr[i] < arr[tailIndices[0]])
 
                // new smallest value
                tailIndices[0] = i;
 
            else if (arr[i] > arr[tailIndices[len - 1]]) {
 
                // arr[i] wants to extend
                // largest subsequence
                prevIndices[i] = tailIndices[len - 1];
                tailIndices[len++] = i;
            }
            else {
 
                // arr[i] wants to be a potential
                // condidate of future subsequence
                // It will replace ceil value in
                // tailIndices
                int pos = GetCeilIndex(arr,
                                       tailIndices, -1, len - 1, arr[i]);
 
                prevIndices[i] = tailIndices[pos - 1];
                tailIndices[pos] = i;
            }
        }
 
        System.out.println("LIS of given input");
 
        for (int i = tailIndices[len - 1]; i >= 0;
             i = prevIndices[i])
            System.out.print(arr[i] + " ");
 
        System.out.println();
 
        return len;
    }
 
    // Driver code
    public static void main(String[] args)
    {
        int arr[] = { 2, 5, 3, 7, 11, 8, 10, 13, 6 };
        int n = arr.length;
 
        System.out.print("LIS size\n" + LongestIncreasingSubsequence(arr, n));
    }
}
 
// This code is contributed by Anant Agarwal.


Python3




# Python implementation to
# find longest increasing
# subsequence
# in O(n Log n) time.
 
# Binary search
def GetCeilIndex(arr, T, l, r, key):
 
    while (r - l > 1):
     
        m = l + (r - l)//2
        if (arr[T[m]] >= key):
            r = m
        else:
            l = m
 
    return r
  
def LongestIncreasingSubsequence(arr, n):
 
    # Add boundary case,
    # when array n is zero
    # Depend on smart pointers
     
    # Initialized with 0
    tailIndices =[0 for i in range(n + 1)] 
 
    # Initialized with -1
    prevIndices =[-1 for i in range(n + 1)] 
     
    # it will always point
    # to empty location
    len = 1
    for i in range(1, n):
     
        if (arr[i] < arr[tailIndices[0]]):
         
            # new smallest value
            tailIndices[0] = i
         
        elif (arr[i] > arr[tailIndices[len-1]]):
         
            # arr[i] wants to extend
            # largest subsequence
            prevIndices[i] = tailIndices[len-1]
            tailIndices[len] = i
            len += 1
         
        else:
         
            # arr[i] wants to be a
            # potential condidate of
            # future subsequence
            # It will replace ceil
            # value in tailIndices
            pos = GetCeilIndex(arr, tailIndices, -1,
                                   len-1, arr[i])
  
            prevIndices[i] = tailIndices[pos-1]
            tailIndices[pos] = i
         
    print("LIS of given input")
    i = tailIndices[len-1]
    while(i >= 0):
        print(arr[i], " ", end ="")
        i = prevIndices[i]
    print()
  
    return len
 
# driver code
arr = [ 2, 5, 3, 7, 11, 8, 10, 13, 6 ]
n = len(arr)
  
print("LIS size\n", LongestIncreasingSubsequence(arr, n))
 
# This code is contributed
# by Anant Agarwal.


C#




// C# implementation to find longest
// increasing subsequence in O(n Log n)
// time.
using System;
 
class GFG {
 
    // Binary search
    static int GetCeilIndex(int[] arr, int[] T, int l,
                            int r, int key)
    {
 
        while (r - l > 1) {
            int m = l + (r - l) / 2;
 
            if (arr[T[m]] >= key)
                r = m;
            else
                l = m;
        }
 
        return r;
    }
 
    static int LongestIncreasingSubsequence(
        int[] arr, int n)
    {
 
        // Add boundary case, when array n is zero
        // Depend on smart pointers
 
        int[] tailIndices = new int[n];
 
        // Initialized with 0
        for (int i = 0; i < n; i++)
            tailIndices[i] = 0;
 
        int[] prevIndices = new int[n];
 
        // initialized with -1
        for (int i = 0; i < n; i++)
            prevIndices[i] = -1;
 
        // it will always point to empty
        // location
        int len = 1;
 
        for (int i = 1; i < n; i++) {
            if (arr[i] < arr[tailIndices[0]])
 
                // new smallest value
                tailIndices[0] = i;
 
            else if (arr[i] > arr[tailIndices[len - 1]]) {
 
                // arr[i] wants to extend
                // largest subsequence
                prevIndices[i] = tailIndices[len - 1];
                tailIndices[len++] = i;
            }
            else {
 
                // arr[i] wants to be a potential
                // condidate of future subsequence
                // It will replace ceil value in
                // tailIndices
                int pos = GetCeilIndex(arr,
                                       tailIndices, -1, len - 1, arr[i]);
 
                prevIndices[i] = tailIndices[pos - 1];
                tailIndices[pos] = i;
            }
        }
 
        Console.Write("LIS of given input");
 
        for (int i = tailIndices[len - 1]; i >= 0;
             i = prevIndices[i])
            Console.Write(arr[i] + " ");
 
        Console.WriteLine();
 
        return len;
    }
 
    // Driver code
    public static void Main()
    {
        int[] arr = { 2, 5, 3, 7, 11, 8, 10, 13, 6 };
        int n = arr.Length;
 
        Console.Write("LIS size\n" + LongestIncreasingSubsequence(arr, n));
    }
}
 
// This code is contributed by nitin mittal.


PHP




<?php
// PHP implementation to find longest increasing
// subsequence in O(n Log n) time.
 
// Binary search
function GetCeilIndex($arr, $T, $l, $r, $key)
{
    while ($r - $l > 1)
    {
        $m = (int)($l + ($r - $l)/2);
        if ($arr[$T[$m]] >= $key)
            $r = $m;
        else
            $l = $m;
    }
 
    return $r;
}
 
function LongestIncreasingSubsequence($arr, $n)
{
    // Add boundary case, when array n is zero
    // Depend on smart pointers
 
    $tailIndices=array_fill(0, $n+1, 0); // Initialized with 0
    $prevIndices=array_fill(0, $n+1, -1); // initialized with -1
 
    $len = 1; // it will always point to empty location
    for ($i = 1; $i < $n; $i++)
    {
        if ($arr[$i] < $arr[$tailIndices[0]])
        {
            // new smallest value
            $tailIndices[0] = $i;
        }
        else if ($arr[$i] > $arr[$tailIndices[$len-1]])
        {
            // arr[i] wants to extend largest subsequence
            $prevIndices[$i] = $tailIndices[$len-1];
            $tailIndices[$len++] = $i;
        }
        else
        {
            // arr[i] wants to be a potential condidate of
            // future subsequence
            // It will replace ceil value in tailIndices
            $pos = GetCeilIndex($arr, $tailIndices, -1,
                                $len-1, $arr[$i]);
 
            $prevIndices[$i] = $tailIndices[$pos-1];
            $tailIndices[$pos] = $i;
        }
    }
 
    echo "LIS of given input\n";
    for ($i = $tailIndices[$len-1]; $i >= 0; $i = $prevIndices[$i])
        echo $arr[$i]." ";
    echo "\n";
 
    return $len;
}
 
// Driver code
$arr = array( 2, 5, 3, 7, 11, 8, 10, 13, 6 );
$n = count($arr);
 
print("LIS size ".LongestIncreasingSubsequence($arr, $n));
 
// This code is contributed by chandan_jnu
?>


Javascript




<script>
 
    // JavaScript implementation to find longest
    // increasing subsequence in O(n Log n) time.
     
    // Binary search
    function GetCeilIndex(arr, T, l, r, key)
    {
   
        while (r - l > 1) {
            let m = l + parseInt((r - l) / 2, 10);
   
            if (arr[T[m]] >= key)
                r = m;
            else
                l = m;
        }
   
        return r;
    }
   
    function LongestIncreasingSubsequence(arr, n)
    {
   
        // Add boundary case, when array n is zero
        // Depend on smart pointers
   
        let tailIndices = new Array(n);
   
        // Initialized with 0
        for (let i = 0; i < n; i++)
            tailIndices[i] = 0;
   
        let prevIndices = new Array(n);
   
        // initialized with -1
        for (let i = 0; i < n; i++)
            prevIndices[i] = -1;
   
        // it will always point to empty
        // location
        let len = 1;
   
        for (let i = 1; i < n; i++) {
            if (arr[i] < arr[tailIndices[0]])
   
                // new smallest value
                tailIndices[0] = i;
   
            else if (arr[i] > arr[tailIndices[len - 1]]) {
   
                // arr[i] wants to extend
                // largest subsequence
                prevIndices[i] = tailIndices[len - 1];
                tailIndices[len++] = i;
            }
            else {
   
                // arr[i] wants to be a potential
                // condidate of future subsequence
                // It will replace ceil value in
                // tailIndices
                let pos = GetCeilIndex(arr,
                          tailIndices, -1, len - 1, arr[i]);
   
                prevIndices[i] = tailIndices[pos - 1];
                tailIndices[pos] = i;
            }
        }
   
        document.write("LIS of given input" + "</br>");
   
        for (let i = tailIndices[len - 1]; i >= 0;
             i = prevIndices[i])
            document.write(arr[i] + " ");
   
        document.write("</br>");
   
        return len;
    }
     
    let arr = [ 2, 5, 3, 7, 11, 8, 10, 13, 6 ];
    let n = arr.length;
 
    document.write("LIS size " +
    LongestIncreasingSubsequence(arr, n));
   
</script>


Output

LIS of given input
13 10 8 7 3 2 
LIS size 6

Time Complexity: O(N*log(N))
Auxiliary Space: O(N)

Exercises:

  1.  You know Kadane‘s algorithm to find maximum sum sub-array. Modify Kadane’s algorithm to trace starting and ending location of maximum sum sub-array.
  2.  Modify Kadane‘s algorithm to find maximum sum sub-array in a circular array. Refer GFG forum for many comments on the question.
  3.  Given two integers A and B as input. Find number of Fibonacci numbers existing in between these two numbers (including A and B). For example, A = 3 and B = 18, there are 4 Fibonacci numbers in between {3,  5, 8, 13}. Do it in O(log K) time, where K is max(A, B). What is your observation?


Similar Reads

Longest Increasing Subsequence using Longest Common Subsequence Algorithm
Given an array arr[] of N integers, the task is to find and print the Longest Increasing Subsequence.Examples: Input: arr[] = {12, 34, 1, 5, 40, 80} Output: 4 {12, 34, 40, 80} and {1, 5, 40, 80} are the longest increasing subsequences.Input: arr[] = {10, 22, 9, 33, 21, 50, 41, 60, 80} Output: 6 Prerequisite: LCS, LISApproach: The longest increasing
12 min read
Longest Monotonically Increasing Subsequence Size (N log N): Simple implementation
Given an array of random numbers, find the longest monotonically increasing subsequence (LIS) in the array. If you want to understand the O(NlogN) approach, it's explained very clearly here. In this post, a simple and time-saving implementation of O(NlogN) approach using stl is discussed. Below is the code for LIS O(NlogN): Implementation: C/C++ Co
5 min read
Longest Increasing Subsequence Size (N log N)
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, in O(N log N). Examples: Input: arr[] = {3, 10, 2, 1, 20}Output: 3Explanation: The longest increasing subsequence is 3, 10, 20 Inpu
8 min read
Longest Bitonic Subsequence in O(n log n)
Given an array arr[0 â€Ķ n-1] containing n positive integers, a subsequence of arr[] is called Bitonic if it is first increasing, then decreasing. Write a function that takes an array as an argument and returns the length of the longest bitonic subsequence. A sequence, sorted in increasing order is considered Bitonic with the decreasing part as empty
15+ min read
Find minimum number of Log value needed to calculate Log upto N
Given an integer N. The task is to find the minimum number of log values needed to calculate all the log values from 1 to N using properties of the logarithm.Examples: Input : N = 6 Output : 3 Value of log1 is already know, i.e. 0. Except this the three log values needed are, log2, log3, log5. Input : N = 4 Output : 2 One of the properties of log f
7 min read
How is the time complexity of Sieve of Eratosthenes is n*log(log(n))?
Pre-requisite: Sieve of Eratosthenes What is Sieve of Eratosthenes algorithm? In order to analyze it, let's take a number n and the task is to print the prime numbers less than n. Therefore, by definition of Sieve of Eratosthenes, for every prime number, it has to check the multiples of the prime and mark it as composite. This process continues unt
3 min read
Longest Increasing Odd Even Subsequence
Given an array of size n. The problem is to find the length of the subsequence in the given array such that all the elements of the subsequence are sorted in increasing order and also they are alternately odd and even. Note that the subsequence could start either with the odd number or with the even number. Examples: Input : arr[] = {5, 6, 9, 4, 7,
8 min read
Printing longest Increasing consecutive subsequence
Given n elements, write a program that prints the longest increasing subsequence whose adjacent element difference is one. Examples: Input : a[] = {3, 10, 3, 11, 4, 5, 6, 7, 8, 12} Output : 3 4 5 6 7 8 Explanation: 3, 4, 5, 6, 7, 8 is the longest increasing subsequence whose adjacent element differs by one. Input : a[] = {6, 7, 8, 3, 4, 5, 9, 10} O
8 min read
Length of the longest increasing subsequence such that no two adjacent elements are coprime
Given an array arr[] of size N. The task is to find the length of the longest subsequence from the given array such that the sequence is strictly increasing and no two adjacent elements are coprime. Note: The elements in the given array are strictly increasing in order (1 &lt;= a[i] &lt;= 105) Examples: Input : a[] = { 1, 2, 3, 4, 5, 6} Output : 3
9 min read
Length of longest increasing subsequence in a string
Given a string S, the task is to find the length of the longest increasing subsequence present in the given string. A sequence of characters placed in increasing order of their ASCII values is called an increasing sequence. Examples: Input: S = "abcfgffs"Output: 6Explanation: Subsequence "abcfgs" is the longest increasing subsequence present in the
7 min read
Article Tags :
Practice Tags :
three90RightbarBannerImg