Largest increasing subsequence of consecutive integers - GeeksforGeeks

22 Jun, 2021
Given an array of n positive integers. We need to find the largest increasing sequence of consecutive positive integers.Examples:  
Input : arr[] = {5, 7, 6, 7, 8} 
Output : Size of LIS = 4
         LIS = 5, 6, 7, 8

Input : arr[] = {5, 7, 8, 7, 5} 
Output : Size of LIS = 2
         LIS = 7, 8
 
This problem can be solved easily by the concept of LIS where each next greater element differ from earlier one by 1. But this will take O(n^2) time complexity.With the use of hashing we can finding the size of longest increasing sequence with consecutive integers in time complexity of O(n).We create a hash table.. Now for each element arr[i], we perform hash[arr[i]] = hash[arr[i] – 1] + 1. So, for every element we know longest consecutive increasing subsequence ending with it. Finally we return maximum value from hash table. 
C++
Java
Python3
C#
Javascript
// C++ implementation of longest continuous increasing// subsequence#include <bits/stdc++.h>using namespace std; // Function for LISint findLIS(int A[], int n){    unordered_map<int, int> hash;     // Initialize result    int LIS_size = 1;    int LIS_index = 0;     hash[A[0]] = 1;     // iterate through array and find    // end index of LIS and its Size    for (int i = 1; i < n; i++) {        hash[A[i]] = hash[A[i] - 1] + 1;        if (LIS_size < hash[A[i]]) {            LIS_size = hash[A[i]];            LIS_index = A[i];        }    }     // print LIS size    cout << "LIS_size = " << LIS_size << "\n";     // print LIS after setting start element    cout << "LIS : ";    int start = LIS_index - LIS_size + 1;    while (start <= LIS_index) {        cout << start << " ";        start++;    }} // driverint main(){    int A[] = { 2, 5, 3, 7, 4, 8, 5, 13, 6 };    int n = sizeof(A) / sizeof(A[0]);    findLIS(A, n);    return 0;}
// Java implementation of longest continuous increasing// subsequenceimport java.util.*; class GFG{ // Function for LISstatic void findLIS(int A[], int n){    Map<Integer, Integer> hash = new HashMap<Integer, Integer>();     // Initialize result    int LIS_size = 1;    int LIS_index = 0;     hash.put(A[0], 1);    // iterate through array and find    // end index of LIS and its Size    for (int i = 1; i < n; i++)    {        hash.put(A[i], hash.get(A[i] - 1)==null? 1:hash.get(A[i] - 1)+1);        if (LIS_size < hash.get(A[i]))        {            LIS_size = hash.get(A[i]);            LIS_index = A[i];        }    }     // print LIS size    System.out.println("LIS_size = " + LIS_size);     // print LIS after setting start element    System.out.print("LIS : ");    int start = LIS_index - LIS_size + 1;    while (start <= LIS_index)    {        System.out.print(start + " ");        start++;    }} // Driver codepublic static void main(String[] args){    int A[] = { 2, 5, 3, 7, 4, 8, 5, 13, 6 };    int n = A.length;    findLIS(A, n);}} // This code is contributed by Princi Singh
# Python3 implementation of longest# continuous increasing subsequence # Function for LISdef findLIS(A, n):    hash = dict()     # Initialize result    LIS_size, LIS_index = 1, 0     hash[A[0]] = 1     # iterate through array and find    # end index of LIS and its Size    for i in range(1, n):         # If the desired key is not present        # in dictionary, it will throw key error,        # to avoid this error this is necessary        if A[i] - 1 not in hash:            hash[A[i] - 1] = 0         hash[A[i]] = hash[A[i] - 1] + 1        if LIS_size < hash[A[i]]:            LIS_size = hash[A[i]]            LIS_index = A[i]         # print LIS size    print("LIS_size =", LIS_size)     # print LIS after setting start element    print("LIS : ", end = "")     start = LIS_index - LIS_size + 1    while start <= LIS_index:        print(start, end = " ")        start += 1 # Driver Codeif __name__ == "__main__":    A = [ 2, 5, 3, 7, 4, 8, 5, 13, 6 ]    n = len(A)    findLIS(A, n) # This code is contributed by sanjeev2552
// C# implementation of longest continuous increasing// subsequenceusing System;using System.Collections.Generic; class GFG{ // Function for LISstatic void findLIS(int []A, int n){    Dictionary<int,int> hash = new Dictionary<int,int>();     // Initialize result    int LIS_size = 1;    int LIS_index = 0;     hash.Add(A[0], 1);         // iterate through array and find    // end index of LIS and its Size    for (int i = 1; i < n; i++)    {        if(hash.ContainsKey(A[i]-1))        {            var val = hash[A[i]-1];            hash.Remove(A[i]);            hash.Add(A[i], val + 1);        }        else        {            hash.Add(A[i], 1);        }        if (LIS_size < hash[A[i]])        {            LIS_size = hash[A[i]];            LIS_index = A[i];        }    }     // print LIS size    Console.WriteLine("LIS_size = " + LIS_size);     // print LIS after setting start element    Console.Write("LIS : ");    int start = LIS_index - LIS_size + 1;    while (start <= LIS_index)    {        Console.Write(start + " ");        start++;    }} // Driver codepublic static void Main(String[] args){    int []A = { 2, 5, 3, 7, 4, 8, 5, 13, 6 };    int n = A.Length;    findLIS(A, n);}} // This code is contributed by 29AjayKumar
<script> // JavaScript implementation of longest continuous increasing// subsequence  // Function for LISfunction findLIS(A, n) {    let hash = new Map();     // Initialize result    let LIS_size = 1;    let LIS_index = 0;     hash.set(A[0], 1);    // iterate through array and find    // end index of LIS and its Size    for (let i = 1; i < n; i++) {        hash.set(A[i], hash.get(A[i] - 1) == null ?        1 : hash.get(A[i] - 1) + 1);        if (LIS_size < hash.get(A[i])) {            LIS_size = hash.get(A[i]);            LIS_index = A[i];        }    }     // print LIS size    document.write("LIS_size = " + LIS_size + "<br>");     // print LIS after setting start element    document.write("LIS : ");    let start = LIS_index - LIS_size + 1;    while (start <= LIS_index) {        document.write(start + " ");        start++;    }} // Driver code let A = [2, 5, 3, 7, 4, 8, 5, 13, 6];let n = A.length;findLIS(A, n); // This code is contributed by gfgking </script>
LIS_size = 5
LIS : 2 3 4 5 6 
 
sanjeev2552
princi singh
29AjayKumar
gfgking
cpp-unordered_map
LIS
Arrays
Hash
Arrays
Hash
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Maximum and minimum of an array using minimum number of comparisons
Top 50 Array Coding Problems for Interviews
Stack Data Structure (Introduction and Program)
Introduction to Arrays
Multidimensional Arrays in Java
Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)
Internal Working of HashMap in Java
Count pairs with given sum
Hashing | Set 1 (Introduction)
Hashing | Set 3 (Open Addressing)