Home
/ Length of the Maximum Continuous Sequence That You Encounter
Length of the Maximum Continuous Sequence That You Encounter
Given an array of integers, find the length of the longest sub-sequence such that elements in the subsequence are consecutive integers, the consecutive numbers can be in any order.
Examples:
Input: arr[] = {1, 9, 3, 10, 4, 20, 2} Output: 4 Explanation: The subsequence 1, 3, 4, 2 is the longest subsequence of consecutive elements
Input: arr[] = {36, 41, 56, 35, 44, 33, 34, 92, 43, 32, 42} Output: 5 Explanation: The subsequence 36, 35, 33, 34, 32 is the longest subsequence of consecutive elements.
Naive Approach:
The idea is to first sort the array and find the longest subarray with consecutive elements. After sorting the array and removing the multiple occurrences of elements, run a loop and keep a count and max (both initially zero). Run a loop from start to end and if the current element is not equal to the previous (element+1) then set the count to 1 else increase the count. Update max with a maximum of count and max.
Illustration:
Input: arr[] = {1, 9, 3, 10, 4, 20, 2}
First sort the array to arrange them in consecutive fashion. arr[] = {1, 2, 3, 4, 9, 10, 20}
Now, store the distinct elements from the sorted array. dist[] = {1, 2, 3, 4, 9, 10, 20}
Initialise countConsecutive with 0 which will increment when arr[i] == arr[i – 1] + 1 is true otherwise countConsecutive will re-initialise by 1.
Maintain a variable ans to store maximum count of consecutive elements so far.
At i = 0:
as i is 0 then re-initialise countConsecutive by 1.
as the above condition is false, therefore re-initialise countConsecutive by 1
countConsecutive = 1
ans = max(ans, countConsecutive) = max(4, 1) = 4
Therefore the longest consecutive subsequence is {1, 2, 3, 4} Hence, ans is 4.
Follow the steps below to solve the problem:
Initialise ans and countConsecutive with 0.
Sort the arr[].
Store the distinct elements in dist[] array by traversing over the arr[].
Now, traverse on the dist[] array to find the count of consecutive elements.
Simultaneously maintain the answer variable.
Below is the implementation of above approach:
C++
#include <bits/stdc++.h>
usingnamespacestd;
intfindLongestConseqSubseq(intarr[], intn)
{
intans = 0, count = 0;
sort(arr, arr + n);
vector<int> v;
v.push_back(arr[0]);
for(inti = 1; i < n; i++) {
if(arr[i] != arr[i - 1])
v.push_back(arr[i]);
}
for(inti = 0; i < v.size(); i++) {
if(i > 0 && v[i] == v[i - 1] + 1)
count++;
else
count = 1;
ans = max(ans, count);
}
returnans;
}
intmain()
{
intarr[] = { 1, 2, 2, 3 };
intn = sizeofarr / sizeofarr[0];
cout << "Length of the Longest contiguous subsequence "
"is "
<< findLongestConseqSubseq(arr, n);
return0;
}
Java
importjava.io.*;
importjava.util.*;
classGFG {
staticintfindLongestConseqSubseq(intarr[], intn)
{
Arrays.sort(arr);
intans = 0, count = 0;
ArrayList<Integer> v = newArrayList<Integer>();
v.add(arr[0]);
for(inti = 1; i < n; i++) {
if(arr[i] != arr[i - 1])
v.add(arr[i]);
}
for(inti = 0; i < v.size(); i++) {
if(i > 0&& v.get(i) == v.get(i - 1) + 1)
count++;
else
count = 1;
ans = Math.max(ans, count);
}
returnans;
}
publicstaticvoidmain(String[] args)
{
intarr[] = { 1, 9, 3, 10, 4, 20, 2};
intn = arr.length;
System.out.println(
"Length of the Longest "
+ "contiguous subsequence is "
+ findLongestConseqSubseq(arr, n));
}
}
Python3
deffindLongestConseqSubseq(arr, n):
ans =0
count =0
arr.sort()
v =[]
v.append(arr[0])
fori inrange(1, n):
if(arr[i] !=arr[i -1]):
v.append(arr[i])
fori inrange(len(v)):
if(i > 0andv[i] ==v[i -1] +1):
count +=1
else:
count =1
ans =max(ans, count)
returnans
arr =[1, 2, 2, 3]
n =len(arr)
print("Length of the Longest contiguous subsequence is",
findLongestConseqSubseq(arr, n))
C#
usingSystem;
usingSystem.Collections.Generic;
classGFG {
staticintfindLongestConseqSubseq(int[] arr, intn)
{
Array.Sort(arr);
intans = 0, count = 0;
List<int> v = newList<int>();
v.Add(10);
for(inti = 1; i < n; i++) {
if(arr[i] != arr[i - 1])
v.Add(arr[i]);
}
for(inti = 0; i < v.Count; i++) {
if(i > 0 && v[i] == v[i - 1] + 1)
count++;
else
count = 1;
ans = Math.Max(ans, count);
}
returnans;
}
staticvoidMain()
{
int[] arr = { 1, 9, 3, 10, 4, 20, 2 };
intn = arr.Length;
Console.WriteLine(
"Length of the Longest "
+ "contiguous subsequence is "
+ findLongestConseqSubseq(arr, n));
}
}
Javascript
<script>
functionfindLongestConseqSubseq(arr, n) {
let ans = 0, count = 0;
arr.sort(function(a, b) { returna - b; })
varv = [];
v.push(arr[0]);
for(let i = 1; i < n; i++) {
if(arr[i] != arr[i - 1])
v.push(arr[i]);
}
for(let i = 0; i < v.length; i++) {
if(i > 0 && v[i] == v[i - 1] + 1)
count++;
else
count = 1;
ans = Math.max(ans, count);
}
returnans;
}
let arr = [1, 2, 2, 3];
let n = arr.length;
document.write(
"Length of the Longest contiguous subsequence is "
+findLongestConseqSubseq(arr, n)
);
</script>
Output
Length of the Longest contiguous subsequence is 3
Time complexity: O(Nlog(N)), Time to sort the array is O(Nlog(N)). Auxiliary space: O(N). Extra space is needed for storing distinct elements.
Longest Consecutive Subsequence using Hashing:
The idea is to use Hashing. We first insert all elements in a Set. Then check all the possible starts of consecutive subsequences.
Illustration:
Below image is the dry run for example arr[] = {1, 9, 3, 10, 4, 20, 2}:
Follow the steps below to solve the problem:
Create an empty hash.
Insert all array elements to hash.
Do the following for every element arr[i]
Check if this element is the starting point of a subsequence. To check this, simply look for arr[i] – 1 in the hash, if not found, then this is the first element of a subsequence.
If this element is the first element, then count the number of elements in the consecutive starting with this element. Iterate from arr[i] + 1 till the last element that can be found.
If the count is more than the previous longest subsequence found, then update this.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
usingnamespacestd;
intfindLongestConseqSubseq(intarr[], intn)
{
unordered_set<int> S;
intans = 0;
for(inti = 0; i < n; i++)
S.insert(arr[i]);
for(inti = 0; i < n; i++) {
if(S.find(arr[i] - 1) == S.end()) {
intj = arr[i];
while(S.find(j) != S.end())
j++;
ans = max(ans, j - arr[i]);
}
}
returnans;
}
intmain()
{
intarr[] = { 1, 9, 3, 10, 4, 20, 2 };
intn = sizeofarr / sizeofarr[0];
cout << "Length of the Longest contiguous subsequence "
"is "
<< findLongestConseqSubseq(arr, n);
return0;
}
Java
importjava.io.*;
importjava.util.*;
classArrayElements {
staticintfindLongestConseqSubseq(intarr[], intn)
{
HashSet<Integer> S = newHashSet<Integer>();
intans = 0;
for(inti = 0; i < n; ++i)
S.add(arr[i]);
for(inti = 0; i < n; ++i) {
if(!S.contains(arr[i] - 1)) {
intj = arr[i];
while(S.contains(j))
j++;
if(ans < j - arr[i])
ans = j - arr[i];
}
}
returnans;
}
publicstaticvoidmain(String args[])
{
intarr[] = { 1, 9, 3, 10, 4, 20, 2};
intn = arr.length;
System.out.println(
"Length of the Longest consecutive subsequence is "
+ findLongestConseqSubseq(arr, n));
}
}
Python3
deffindLongestConseqSubseq(arr, n):
s =set()
ans =0
forele inarr:
s.add(ele)
fori inrange(n):
if(arr[i]-1) notins:
j =arr[i]
while(j ins):
j +=1
ans =max(ans, j-arr[i])
returnans
if__name__ =='__main__':
n =7
arr =[1, 9, 3, 10, 4, 20, 2]
print("Length of the Longest contiguous subsequence is ",
findLongestConseqSubseq(arr, n))
C#
usingSystem;
usingSystem.Collections.Generic;
publicclassArrayElements {
publicstaticintfindLongestConseqSubseq(int[] arr,
intn)
{
HashSet<int> S = newHashSet<int>();
intans = 0;
for(inti = 0; i < n; ++i) {
S.Add(arr[i]);
}
for(inti = 0; i < n; ++i) {
if(!S.Contains(arr[i] - 1)) {
intj = arr[i];
while(S.Contains(j)) {
j++;
}
if(ans < j - arr[i]) {
ans = j - arr[i];
}
}
}
returnans;
}
publicstaticvoidMain(string[] args)
{
int[] arr = newint[] { 1, 9, 3, 10, 4, 20, 2 };
intn = arr.Length;
Console.WriteLine(
"Length of the Longest consecutive subsequence is "
+ findLongestConseqSubseq(arr, n));
}
}
Javascript
<script>
functionfindLongestConseqSubseq(arr, n) {
let S = newSet();
let ans = 0;
for(let i = 0; i < n; i++)
S.add(arr[i]);
for(let i = 0; i < n; i++)
{
if(!S.has(arr[i] - 1))
{
let j = arr[i];
while(S.has(j))
j++;
ans = Math.max(ans, j - arr[i]);
}
}
returnans;
}
let arr = [1, 9, 3, 10, 4, 20, 2];
let n = arr.length;
document.write("Length of the Longest contiguous subsequence is "
+ findLongestConseqSubseq(arr, n));
</script>
Output
Length of the Longest contiguous subsequence is 4
Time complexity: O(N), Only one traversal is needed and the time complexity is O(n) under the assumption that hash insert and search takes O(1) time. Auxiliary space: O(N), To store every element in the hashmap O(n) space is needed
Longest Consecutive Subsequence using Priority Queue:
The Idea is to use Priority Queue. Using priority queue it will sort the elements and eventually it will help to find consecutive elements.
Illustration:
Input: arr[] = {1, 9, 3, 10, 4, 20, 2}
Insert all the elements in the Priority Queue:
1
2
3
4
9
10
20
Initialise variable prev with first element of priority queue, prev will contain last element has been picked and it will help to check whether the current element is contributing for consecutive sequence or not.
prev = 1, countConsecutive = 1, ans = 1
Run the algorithm till the priority queue becomes empty.
2
3
4
9
10
20
current element is 2
prev + 1 == 2, therefore increment countConsecutive by 1
cout << "Length of the Longest consecutive subsequence "
"is "
<< findLongestConseqSubseq(arr, n);
return0;
}
Java
importjava.io.*;
importjava.util.PriorityQueue;
publicclassLongset_Sub {
staticintfindLongestConseqSubseq(intarr[], intN)
{
PriorityQueue<Integer> pq
= newPriorityQueue<Integer>();
for(inti = 0; i < N; i++) {
pq.add(arr[i]);
}
intprev = pq.poll();
intc = 1;
intmax = 1;
for(inti = 1; i < N; i++) {
if(pq.peek() - prev > 1) {
c = 1;
prev = pq.poll();
}
elseif(pq.peek() - prev == 0) {
prev = pq.poll();
}
else{
c++;
prev = pq.poll();
}
if(max < c) {
max = c;
}
}
returnmax;
}
publicstaticvoidmain(String args[])
throwsIOException
{
intarr[] = { 1, 9, 3, 10, 4, 20, 2};
intn = arr.length;
System.out.println(
"Length of the Longest consecutive subsequence is "
+ findLongestConseqSubseq(arr, n));
}
}
Python3
importbisect
deffindLongestConseqSubseq(arr, N):
pq =[]
fori inrange(N):
bisect.insort(pq, arr[i])
prev =pq[0]
pq.pop(0)
c =1
max=1
while(len(pq)):
if(pq[0] -prev > 1):
c =1
prev =pq[0]
pq.pop(0)
elif(pq[0] -prev ==0):
prev =pq[0]
pq.pop(0)
else:
c =c +1
prev =pq[0]
pq.pop(0)
if(max< c):
max=c
returnmax
arr =[1, 9, 3, 10, 4, 20, 2]
n =7
print("Length of the Longest consecutive subsequence is {}".format(
findLongestConseqSubseq(arr, n)))
C#
usingSystem;
usingSystem.Collections.Generic;
classGFG {
staticintfindLongestConseqSubseq(int[] arr, intN)
{
List<int> pq = newList<int>();
for(inti = 0; i < N; i++) {
pq.Add(arr[i]);
pq.Sort();
}
intprev = pq[0];
intc = 1;
intmax = 1;
for(inti = 1; i < N; i++) {
if(pq[0] - prev > 1) {
c = 1;
prev = pq[0];
pq.RemoveAt(0);
}
elseif(pq[0] - prev == 0) {
prev = pq[0];
pq.RemoveAt(0);
}
else{
c++;
prev = pq[0];
pq.RemoveAt(0);
}
if(max < c) {
max = c;
}
}
returnmax;
}
publicstaticvoidMain()
{
int[] arr = { 1, 9, 3, 10, 4, 20, 2 };
intn = arr.Length;
Console.WriteLine(
"Length of the Longest consecutive subsequence is "
+ findLongestConseqSubseq(arr, n));
}
}
Output
Length of the Longest consecutive subsequence is 4
Time Complexity: O(N*log(N)), Time required to push and pop N elements is logN for each element. Auxiliary Space: O(N), Space required by priority queue to store N elements.