The Wayback Machine - https://web.archive.org/web/20241225114401/https://www.geeksforgeeks.org/longest-consecutive-subsequence/
Open In App

Longest Consecutive Subsequence

Last Updated : 24 Dec, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Given an array of integers, the task is to 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[] = [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. Run a loop from start to end and if the current element is a duplicate of previous element then skip this element.

Otherwise check if current element is equal to the (previous element + 1) then increase the consecutive count else set the consecutive count to 1. Update result with a maximum of current consecutive count and result. 

C++
// C++ program to find longest contiguous subsequence
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

int findLongestConseqSubseq(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 << findLongestConseqSubseq(arr);
    return 0;
}
Java
// Java program to find longest contiguous subsequence
import java.util.Arrays;

class GfG {
    static int findLongestConseqSubseq(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(findLongestConseqSubseq(arr));
    }
}
Python
# Python program to find longest contiguous subsequence

def findLongestConseqSubseq(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(findLongestConseqSubseq(arr))
C#
// C# program to find longest contiguous subsequence
using System;
using System.Linq;

class GfG {
    static int findLongestConseqSubseq(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(findLongestConseqSubseq(arr));
    }
}
JavaScript
// JavaScript program to find longest contiguous subsequence

function findLongestConseqSubseq(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(findLongestConseqSubseq(arr));

Output
6

[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 contiguous subsequence
#include <iostream>
#include <unordered_set>
#include <vector>
using namespace std;

int findLongestConseqSubseq(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 << findLongestConseqSubseq(arr);
    return 0;
}
Java
// Java program to find longest contiguous subsequence
import java.util.*;

class GfG {
    static int findLongestConseqSubseq(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(findLongestConseqSubseq(arr));
    }
}
Python
# Python program to find longest contiguous subsequence

def findLongestConseqSubseq(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 optimal 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(findLongestConseqSubseq(arr))
C#
// C# program to find longest contiguous subsequence
using System;
using System.Collections.Generic;

class GfG {
    static int findLongestConseqSubseq(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(findLongestConseqSubseq(arr));
    }
}
JavaScript
// JavaScript program to find longest contiguous subsequence

function findLongestConseqSubseq(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(findLongestConseqSubseq(arr));

Output
6




Next Article

Similar Reads

three90RightbarBannerImg