VOOZH about

URL: https://www.geeksforgeeks.org/dsa/longest-consecutive-subsequence/

⇱ Longest Consecutive Subsequence - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Longest Consecutive Subsequence

Last Updated : 14 Jun, 2026

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 longest consecutive subsequence [2, 6, 1, 4, 5, 3].

Input: arr[] = [1,1,1,2,2,3]
Output: 3
Explanation: The subsequence [1, 2,3] 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.

Steps

1) Sort the array in ascending order.

2) 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.

3) After iterating over all the elements, return the result.


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.

Steps

  1. Store all the elements in a hash set to allow quick lookup.
  2. Find the starting point of consecutive sequences.
  3. Traverse through each element and check if this element is starting point or not. We mainly check if X - 1 is present in the set or not. If, not present that means X can become the starting point of longest consecutive subsequence.
  4. Once we find a starting point, count the sequence length by checking if X + 1, X + 2....is present in the set or not.
  5. Increment the count.

Output
6
Comment