Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • DSA
  • Interview Problems on Hash
  • Practice Hash
  • MCQs on Hash
  • Hashing Tutorial
  • Hash Function
  • Index Mapping
  • Collision Resolution
  • Open Addressing
  • Separate Chaining
  • Quadratic probing
  • Double Hashing
  • Load Factor and Rehashing
  • Advantage & Disadvantage
Open In App
Next Article:
Longest Consecutive Subsequence
Next article icon

Longest Consecutive Subsequence

Last Updated : 31 Dec, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report
Try it on GfG Practice
redirect icon

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.

Table of Content

  • [Naive Approach] Using Sorting - O(n*log n) Time and O(1) Space
  • [Expected Approach] Using Hashing - O(n) Time and O(n) Space

[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)); 

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 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)); 

Output
6



Next Article
Longest Consecutive Subsequence

K

kartik
Improve
Article Tags :
  • Sorting
  • Hash
  • DSA
  • Arrays
  • Amazon
  • Walmart
  • Zoho
  • Linkedin
  • subsequence
  • Arrays
  • Hash
Practice Tags :
  • Amazon
  • Linkedin
  • Walmart
  • Zoho
  • Arrays
  • Arrays
  • Hash
  • Hash
  • Sorting

Similar Reads

    Longest Increasing consecutive subsequence
    Given N elements, write a program that prints the length of the longest increasing consecutive subsequence. Examples: Input : a[] = {3, 10, 3, 11, 4, 5, 6, 7, 8, 12} Output : 6 Explanation: 3, 4, 5, 6, 7, 8 is the longest increasing subsequence whose adjacent element differs by one. Input : a[] = {6
    10 min read
    Longest Bitonic Subsequence
    Given an array arr[] containing n positive integers, a subsequence of numbers is called bitonic if it is first strictly increasing, then strictly decreasing. The task is to find the length of the longest bitonic subsequence. Note: Only strictly increasing (no decreasing part) or a strictly decreasin
    15+ min read
    Longest Common Subsequence (LCS)
    Given two strings, s1 and s2, the task is to find the length of the Longest Common Subsequence. If there is no common subsequence, return 0. A subsequence is a string generated from the original string by deleting 0 or more characters, without changing the relative order of the remaining characters.
    15+ min read
    Longest Increasing consecutive subsequence | Set-2
    Given an array arr[] of N elements, the task is to find the length of the longest increasing subsequence whose adjacent element difference is one. Examples: Input: arr[] = {3, 10, 3, 11, 4, 5, 6, 7, 8, 12} Output: 6 Explanation: The subsequence {3, 4, 5, 6, 7, 8} is the longest increasing subsequenc
    5 min read
    Printing longest Increasing consecutive subsequence
    Given n elements, write a program that prints the longest increasing subsequence whose adjacent element difference is one. Examples: Input : a[] = {3, 10, 3, 11, 4, 5, 6, 7, 8, 12} Output : 3 4 5 6 7 8 Explanation: 3, 4, 5, 6, 7, 8 is the longest increasing subsequence whose adjacent element differs
    8 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences