Longest Consecutive Subsequence
Last Updated :
31 Dec, 2024
Given an array of integers, the task is to find the length of the longest subsequence such that elements in the subsequence are consecutive integers, the consecutive numbers can be in any order.
Examples:
Input: arr[] = [2, 6, 1, 9, 4, 5, 3]
Output: 6
Explanation: The consecutive numbers here are from 1 to 6. These 6 numbers form the longest consecutive subsequence [2, 6, 1, 4, 5, 3].
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] Using Sorting - O(n*log n) Time and O(1) Space
The idea is to sort the array and find the longest subarray with consecutive elements. Initialize the consecutive count with 1 and start iterating over the sorted array from the second element. For each element arr[i], we can have three cases:
- arr[i] = arr[i - 1], then the ith element is simply a duplicate element so skip it.
- arr[i] = arr[i - 1] + 1, then increase the consecutive count and update result if consecutive count is greater than result.
- arr[i] > arr[i - 1], then reset the consecutive count to 1.
After iterating over all the elements, return the result.
C++
// C++ program to find longest consecutive subsequence
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int longestConsecutive(vector<int>& arr) {
// sort the array
sort(arr.begin(), arr.end());
int res = 1, cnt = 1;
// find the maximum length by traversing the array
for (int i = 1; i < arr.size(); i++) {
// Skip duplicates
if (arr[i] == arr[i-1])
continue;
// Check if the current element is equal
// to previous element + 1
if (arr[i] == arr[i - 1] + 1) {
cnt++;
}
else {
// reset the count
cnt = 1;
}
// update the result
res = max(res, cnt);
}
return res;
}
int main() {
vector<int> arr = { 2, 6, 1, 9, 4, 5, 3};
cout << longestConsecutive(arr);
return 0;
}
C
// C program to find longest consecutive subsequence
#include <stdio.h>
#include <stdlib.h>
// Function to compare two integers (used in qsort)
int compare(const void *a, const void *b) {
return (*(int*)a - *(int*)b);
}
// Function to find the longest consecutive subsequence
int longestConsecutive(int arr[], int n) {
// Sort the array
qsort(arr, n, sizeof(int), compare);
int res = 1, cnt = 1;
// Find the maximum length by traversing the array
for (int i = 1; i < n; i++) {
// Skip duplicates
if (arr[i] == arr[i - 1])
continue;
// Check if the current element is equal
// to previous element + 1
if (arr[i] == arr[i - 1] + 1) {
cnt++;
}
else {
// Reset the count
cnt = 1;
}
// Update the result
if (cnt > res) {
res = cnt;
}
}
return res;
}
int main() {
int arr[] = { 2, 6, 1, 9, 4, 5, 3 };
int n = sizeof(arr) / sizeof(arr[0]);
printf("%d\n", longestConsecutive(arr, n));
return 0;
}
Java
// Java program to find longest consecutive subsequence
import java.util.Arrays;
class GfG {
static int longestConsecutive(int[] arr) {
// Sort the array
Arrays.sort(arr);
int res = 1, cnt = 1;
// Find the maximum length by traversing the array
for (int i = 1; i < arr.length; i++) {
// Skip duplicates
if (arr[i] == arr[i - 1])
continue;
// Check if the current element is equal
// to previous element + 1
if (arr[i] == arr[i - 1] + 1) {
cnt++;
} else {
// Reset the count
cnt = 1;
}
// Update the result
res = Math.max(res, cnt);
}
return res;
}
public static void main(String[] args) {
int[] arr = { 2, 6, 1, 9, 4, 5, 3 };
System.out.println(longestConsecutive(arr));
}
}
Python
# Python program to find longest consecutive subsequence
def longestConsecutive(arr):
# Sort the array
arr.sort()
res = 1
cnt = 1
# Find the maximum length by traversing the array
for i in range(1, len(arr)):
# Skip duplicates
if arr[i] == arr[i - 1]:
continue
# Check if the current element is equal
# to previous element + 1
if arr[i] == arr[i - 1] + 1:
cnt += 1
else:
# Reset the count
cnt = 1
# Update the result
res = max(res, cnt)
return res
if __name__ == "__main__":
arr = [2, 6, 1, 9, 4, 5, 3]
print(longestConsecutive(arr))
C#
// C# program to find longest consecutive subsequence
using System;
using System.Linq;
class GfG {
static int longestConsecutive(int[] arr) {
// Sort the array
Array.Sort(arr);
int res = 1, cnt = 1;
// Find the maximum length by traversing the array
for (int i = 1; i < arr.Length; i++) {
// Skip duplicates
if (arr[i] == arr[i - 1])
continue;
// Check if the current element is equal
// to previous element + 1
if (arr[i] == arr[i - 1] + 1) {
cnt++;
}
else {
// Reset the count
cnt = 1;
}
// Update the result
res = Math.Max(res, cnt);
}
return res;
}
static void Main(string[] args) {
int[] arr = { 2, 6, 1, 9, 4, 5, 3 };
Console.WriteLine(longestConsecutive(arr));
}
}
JavaScript
// JavaScript program to find longest consecutive subsequence
function longestConsecutive(arr) {
// Sort the array
arr.sort((a, b) => a - b);
let res = 1, cnt = 1;
// Find the maximum length by traversing the array
for (let i = 1; i < arr.length; i++) {
// Skip duplicates
if (arr[i] === arr[i - 1])
continue;
// Check if the current element is equal
// to previous element + 1
if (arr[i] === arr[i - 1] + 1) {
cnt++;
}
else {
// Reset the count
cnt = 1;
}
// Update the result
res = Math.max(res, cnt);
}
return res;
}
// Driver Code
const arr = [2, 6, 1, 9, 4, 5, 3];
console.log(longestConsecutive(arr));
[Expected Approach] Using Hashing - O(n) Time and O(n) Space
The idea is to use Hashing. We first insert all elements in a Hash Set. Then, traverse over all the elements and check if the current element can be a starting element of a consecutive subsequence. If it is then start from X and keep on removing elements X + 1, X + 2 .... to find a consecutive subsequence.
To check if the current element, say X can be a starting element, check if (X - 1) is present in the set. If (X - 1) is present in the set, then X cannot be starting of a consecutive subsequence.
C++
// C++ program to find longest consecutive subsequence
#include <iostream>
#include <unordered_set>
#include <vector>
using namespace std;
int longestConsecutive(vector<int> &arr) {
unordered_set<int> st;
int res = 0;
// Hash all the array elements
for (int val: arr)
st.insert(val);
// check each possible sequence from the start then update optimal length
for (int val: arr) {
// if current element is the starting element of a sequence
if (st.find(val) != st.end() && st.find(val-1) == st.end()) {
// Then check for next elements in the sequence
int cur = val, cnt = 0;
while (st.find(cur) != st.end()) {
// Remove this number to avoid recomputation
st.erase(cur);
cur++;
cnt++;
}
// update optimal length
res = max(res, cnt);
}
}
return res;
}
int main() {
vector<int> arr = {2, 6, 1, 9, 4, 5, 3};
cout << longestConsecutive(arr);
return 0;
}
Java
// Java program to find longest consecutive subsequence
import java.util.*;
class GfG {
static int longestConsecutive(int[] arr) {
Set<Integer> st = new HashSet<>();
int res = 0;
// Hash all the array elements
for (int val : arr)
st.add(val);
// Check each possible sequence from the start then update optimal length
for (int val : arr) {
// If current element is the starting element of a sequence
if (st.contains(val) && !st.contains(val - 1)) {
// Then check for next elements in the sequence
int cur = val, cnt = 0;
while (st.contains(cur)) {
// Remove this number to avoid recomputation
st.remove(cur);
cur++;
cnt++;
}
// Update optimal length
res = Math.max(res, cnt);
}
}
return res;
}
public static void main(String[] args) {
int[] arr = {2, 6, 1, 9, 4, 5, 3};
System.out.println(longestConsecutive(arr));
}
}
Python
# Python program to find longest consecutive subsequence
def longestConsecutive(arr):
st = set()
res = 0
# Hash all the array elements
for val in arr:
st.add(val)
# Check each possible sequence from the start
# then update length
for val in arr:
# If current element is the starting element of a sequence
if val in st and (val - 1) not in st:
# Then check for next elements in the sequence
cur = val
cnt = 0
while cur in st:
# Remove this number to avoid recomputation
st.remove(cur)
cur += 1
cnt += 1
# Update optimal length
res = max(res, cnt)
return res
if __name__ == "__main__":
arr = [2, 6, 1, 9, 4, 5, 3]
print(longestConsecutive(arr))
C#
// C# program to find longest consecutive subsequence
using System;
using System.Collections.Generic;
class GfG {
static int longestConsecutive(int[] arr) {
HashSet<int> st = new HashSet<int>();
int res = 0;
// Hash all the array elements
foreach (int val in arr)
st.Add(val);
// Check each possible sequence from the start then update optimal length
foreach (int val in arr) {
// If current element is the starting element of a sequence
if (st.Contains(val) && !st.Contains(val - 1)) {
// Then check for next elements in the sequence
int cur = val, cnt = 0;
while (st.Contains(cur)) {
// Remove this number to avoid recomputation
st.Remove(cur);
cur++;
cnt++;
}
// Update optimal length
res = Math.Max(res, cnt);
}
}
return res;
}
static void Main(string[] args) {
int[] arr = {2, 6, 1, 9, 4, 5, 3};
Console.WriteLine(longestConsecutive(arr));
}
}
JavaScript
// JavaScript program to find longest consecutive subsequence
function longestConsecutive(arr) {
let st = new Set();
let res = 0;
// Hash all the array elements
for (let val of arr) {
st.add(val);
}
// Check each possible sequence from the start then update
// optimal length
for (let val of arr) {
// If current element is the starting element of a sequence
if (st.has(val) && !st.has(val - 1)) {
// Then check for next elements in the sequence
let cur = val, cnt = 0;
while (st.has(cur)) {
// Remove this number to avoid recomputation
st.delete(cur);
cur++;
cnt++;
}
// Update optimal length
res = Math.max(res, cnt);
}
}
return res;
}
// Driver Code
const arr = [2, 6, 1, 9, 4, 5, 3];
console.log(longestConsecutive(arr));
Longest Consecutive Subsequence | Video
Longest Consecutive Subsequence
Similar Reads
Interview Preparation
Practice @Geeksforgeeks
Data Structures
Algorithms
Programming Languages
Web Technologies
Computer Science Subjects
Data Science & ML
Tutorial Library
GATE CS