Open In App

Largest increasing subsequence of consecutive integers

Last Updated : 22 Jul, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

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.

Implementation:

C++





Java





Python3





C#





Javascript





Output: 

LIS_size = 5
LIS : 2 3 4 5 6 

 

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



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads