Table of contents
1.
Introduction
2.
Naive Approach
3.
Longest Consecutive Subsequence using Sorting without Removing Duplicate Elements:
3.1.
C++
3.2.
Java
3.3.
Python
3.4.
C#
3.5.
Javascript
4.
Longest Consecutive Subsequence using Hashing:
4.1.
C++
4.2.
Java
4.3.
Python
4.4.
C#
4.5.
Javascript
5.
Longest Consecutive Subsequence using Priority Queue:
5.1.
C++
5.2.
Java
5.3.
Python
5.4.
C#
5.5.
Javascript
6.
Longest Consecutive Subsequence using Dynamic Programming:
6.1.
C++
6.2.
Java
6.3.
Python
6.4.
C#
6.5.
Javascript
7.
Longest Consecutive Subsequence using Hashing:
7.1.
C++
7.2.
Java
7.3.
Python
7.4.
C#
7.5.
Javascript
8.
Frequently Asked Questions
8.1.
Can I find the longest consecutive subsequence of an array without sorting the array?
8.2.
How does the longest common sequence work?
8.3.
Can there be more than one longest common subsequence?
8.4.
How do you find the longest consecutive sequence in an array?
8.5.
Which is known to be the longest sequence or path?
9.
Conclusion
Last Updated: Oct 8, 2024
Medium

Longest Consecutive Sequence

Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

A "Longest Consecutive Sequence" refers to a consecutive sequence of numbers within a given set where each number follows the previous one without any gaps. The aim is to find the longest sequence of consecutive numbers within the set.

longest consecutive sequence

A subarray is a continuous set of elements of an array, while the subsequence can contain array elements in any order. Subsequence doesn’t demand elements in a continuous manner. Let’s make it more evident with the help of the example below:

Suppose we are having an array arr = [1, 3, 5, 9, 10, 8, 6, 7].Now the subarray will be like [1,3,5] or [10, 8, 6] but the subsequence can include [1, 10, 7] or [5, 7].

The problem statement in your interviews for this problem will be stated like this:

Given an array of integers, print the longest subsequence such that elements of the subsequence are consecutive integers, although they can be in any order.

Let’s see some examples to understand the problem better:

Suppose we are having an array of integers given below:

1

9

3

10

4

20

2

Now you have to give the longest consecutive subsequence as output which will be [1, 3, 4, 2]. I hope you got the problem statement clearly, so let’s move toward solving it.

Naive Approach

The naive approach to finding the longest consecutive sequence in an array involves iterating over each element in the array and checking if the next consecutive number is present in the array. If the next consecutive number is present, we continue checking for the next consecutive number until there are no more consecutive numbers. We keep track of the length of the consecutive sequence and update the longest consecutive sequence found so far.

 

Here is the pseudocode for the naive approach:

int findLongestConsecutiveSequence(vector<int>& nums) {
    int longestSequence = 0;
    for (int num : nums) {
        int currentSequenceLength = 1;
        int currentNum = num;
        while (find(nums.begin(), nums.end(), currentNum + 1) != nums.end()) {
            currentSequenceLength++;
            currentNum++;
        }
        longestSequence = max(longestSequence, currentSequenceLength);
    }
    return longestSequence;
}

 

In this approach, we iterate over each element in the array, and for each element, we iterate over the array again to find the length of the consecutive sequence starting from that element. The time complexity of this approach is O(n^2), where n is the length of the array. It is not the most efficient approach, but it can be useful for small arrays or as a starting point for more optimized solutions.

Longest Consecutive Subsequence using Sorting without Removing Duplicate Elements:

In this approach, sorting is used without removing any duplicate elements from the array means we will also consider the duplicate elements. Here are the following steps to understand this approach:

Step 1: If the length of the array is 0, return 0. Because the length of the longest consecutive subsequence will also be 0.

Step 2: Sort the given array, and any sorting method can be used here to sort the array.

Step 3: Start an iteration of the array from 1 to n and start comparing the current with the previous element.

Step 4: If both the elements are the same, then continue (skip the elements as these two elements are duplicates).

Step 5: If the difference between the current and previous element is 1, then increment the count of the longest consecutive subsequence and update the max_length to the maximum by comparing it with the count.

Step 6: Else set the count to 1, as the length of the longest consecutive subsequence is broken. So we need to start with 1 from the next element.

Step 7: Return the max_length, as this will store the length of the longest consecutive subsequence.

Let's look at the implementation of the above-explained approach :

  • C++
  • Java
  • Python
  • C#
  • Javascript

C++

#include <bits/stdc++.h>
using namespace std;

int longestConsecutive(vector < int > & nums) {
int n = nums.size();

/* if n is 0, length of longest consecutive subsequence will also be 0. */
if (n == 0) return 0;

// use sort() function to sort the array.
sort(nums.begin(), nums.end());

/* create two variables, to maintain the count and the maximum length of longest consecutive subsequence */
int count = 1, max_length = 1;

// Iteration from 1 to n
for (int i = 1; i < n; i++) {

// if the current and previous elements are the same, just skip
if (nums[i] == nums[i - 1]) continue;

/* if the difference of current and previous elements is 1, increment the count and update the value of max_length with the maximum. */
if (nums[i] - nums[i - 1] == 1) {
count++;
max_length = max(count, max_length);
}

// Else set the count to 1, and start with 1 from the next element.
else count = 1;
}

return max_length;
}

int main() {
vector <int> input = { 33, 20, 34, 30, 35 };

cout << "Length of Longest Consecutive Subsequence is " << longestConsecutive(input);
return 0;
}
You can also try this code with Online C++ Compiler
Run Code

Java

import java.util.Arrays;

public class Main {
public static int longestConsecutive(int[] nums) {
int n = nums.length;
if (n == 0) return 0;

Arrays.sort(nums);

int count = 1, max_length = 1;

for (int i = 1; i < n; i++) {
if (nums[i] == nums[i - 1]) continue;

if (nums[i] - nums[i - 1] == 1) {
count++;
max_length = Math.max(count, max_length);
} else {
count = 1;
}
}

return max_length;
}

public static void main(String[] args) {
int[] input = {33, 20, 34, 30, 35};
System.out.println("Length of Longest Consecutive Subsequence is " + longestConsecutive(input));
}
}
You can also try this code with Online Java Compiler
Run Code

Python

def longestConsecutive(nums):
n = len(nums)
if n == 0:
return 0

nums.sort()

count = 1
max_length = 1

for i in range(1, n):
if nums[i] == nums[i - 1]:
continue

if nums[i] - nums[i - 1] == 1:
count += 1
max_length = max(count, max_length)
else:
count = 1

return max_length

input = [33, 20, 34, 30, 35]
print("Length of Longest Consecutive Subsequence is", longestConsecutive(input))
You can also try this code with Online Python Compiler
Run Code

C#

using System;
using System.Linq;

class Program {
public static int LongestConsecutive(int[] nums) {
int n = nums.Length;
if (n == 0) return 0;

Array.Sort(nums);

int count = 1, max_length = 1;

for (int i = 1; i < n; i++) {
if (nums[i] == nums[i - 1]) continue;

if (nums[i] - nums[i - 1] == 1) {
count++;
max_length = Math.Max(count, max_length);
} else {
count = 1;
}
}

return max_length;
}

static void Main() {
int[] input = {33, 20, 34, 30, 35};
Console.WriteLine("Length of Longest Consecutive Subsequence is " + LongestConsecutive(input));
}
}

Javascript

function longestConsecutive(nums) {
const n = nums.length;
if (n === 0) return 0;

nums.sort((a, b) => a - b);

let count = 1;
let max_length = 1;

for (let i = 1; i < n; i++) {
if (nums[i] === nums[i - 1]) continue;

if (nums[i] - nums[i - 1] === 1) {
count++;
max_length = Math.max(count, max_length);
} else {
count = 1;
}
}

return max_length;
}

const input = [33, 20, 34, 30, 35];
console.log("Length of Longest Consecutive Subsequence is " + longestConsecutive(input));
You can also try this code with Online Javascript Compiler
Run Code


Output:

Longest Consecutive Subsequence using sorting - Output

Longest Consecutive Subsequence using Hashing:

Hashing implies you can solve this problem using a set or map to decrease the time complexity. Let’s see the steps:- 

Step 1. You need to Store all the elements of the array in a set.

Step 2. Now, for every element in the set, you have to check whether it can be the starting element of the longest consecutive subsequence or not.To do so, for every arr[i] in set check if arr[i]-1 is present.If no, then it will be the starting element of the longest consecutive subsequence.

Step 3. Now iterate in the set to find all those numbers which are consecutive to arr[i] and store the count.

Step 4. Update the value of ans if this count is greater than the previous one.

 

Let’s understand it better using code.

Also checkout HashSet.

Below is the implementation of above approach:
 

  • C++
  • Java
  • Python
  • C#
  • Javascript

C++

C++
#include <iostream>
#include <unordered_set>
using namespace std;



int lenSubsq(vector<int> &arr, int n) {
// Storing length of longest consecutive sequence.
int ans = 0;
// Storing the length of the current consecutive Sequence.
int count = 0;
// Storing all the unique elements of an array.
unordered_set<int> set;

for (int i = 0; i < n; i++) {
set.insert(arr[i]);
}

for (int i = 0; i < n; i++) {
int prevElem = arr[i] - 1;
if (set.find(prevElem) == set.end()) {
int j = arr[i];

while (set.find(j) != set.end()) {
// The next consecutive element will be j + 1.
j++;
}

// Update maximum length of consecutive sequence.
ans = max(ans, j - arr[i]);
}
}

return ans;
}



int main()
{
vector<int> input = { 33, 20, 34, 30, 35};
int n = 5;

cout << "Length of maximum consecutive subsequence will be "
<<lenSubsq(input, n);

return 0;
}
You can also try this code with Online C++ Compiler
Run Code

Java

import java.util.HashSet;
import java.util.Set;

public class Main {
public static int lenSubsq(int[] arr, int n) {
int ans = 0;
Set<Integer> set = new HashSet<>();

for (int num : arr) {
set.add(num);
}

for (int num : arr) {
if (!set.contains(num - 1)) {
int j = num;
while (set.contains(j)) {
j++;
}
ans = Math.max(ans, j - num);
}
}

return ans;
}

public static void main(String[] args) {
int[] input = {33, 20, 34, 30, 35};
int n = input.length;

System.out.println("Length of maximum consecutive subsequence will be " + lenSubsq(input, n));
}
}
You can also try this code with Online Java Compiler
Run Code

Python

def lenSubsq(arr, n):
ans = 0
set_ = set(arr)

for num in arr:
if num - 1 not in set_:
j = num
while j in set_:
j += 1
ans = max(ans, j - num)

return ans

input = [33, 20, 34, 30, 35]
n = len(input)

print("Length of maximum consecutive subsequence will be", lenSubsq(input, n))
You can also try this code with Online Python Compiler
Run Code

C#

using System;
using System.Collections.Generic;

class Program {
public static int LenSubsq(int[] arr, int n) {
int ans = 0;
HashSet<int> set = new HashSet<int>();

foreach (int num in arr) {
set.Add(num);
}

foreach (int num in arr) {
if (!set.Contains(num - 1)) {
int j = num;
while (set.Contains(j)) {
j++;
}
ans = Math.Max(ans, j - num);
}
}

return ans;
}

static void Main() {
int[] input = {33, 20, 34, 30, 35};
int n = input.Length;

Console.WriteLine("Length of maximum consecutive subsequence will be " + LenSubsq(input, n));
}
}

Javascript

function lenSubsq(arr, n) {
let ans = 0;
const set = new Set(arr);

for (const num of arr) {
if (!set.has(num - 1)) {
let j = num;
while (set.has(j)) {
j++;
}
ans = Math.max(ans, j - num);
}
}

return ans;
}

const input = [33, 20, 34, 30, 35];
const n = input.length;

console.log("Length of maximum consecutive subsequence will be " + lenSubsq(input, n));
You can also try this code with Online Javascript Compiler
Run Code

Output: 

Length of maximum consecutive subsequence will be 3.

Longest Consecutive Subsequence using Priority Queue:

In this approach, Priority Queue will be used to find the length of the longest consecutive subsequence. Here are the following steps to understand this approach:

Step 1: If the length of the array is 0, return 0. Because the length of the longest consecutive subsequence will also be 0.

Step 2: Create a min heap, that will store the top element as the minimum and we can retrieve this minimum element anytime.

Step 3: Start an iteration from 0 to n and insert every element in min heap (or priority queue).

Step 4: After the above iteration, start another loop to iterate the min heap until it gets empty. In this loop, we will retrieve the minimum element (top element of the min heap) and pop it. And compare the current element (top of the min heap) and retrieved element.

Step 5: If both the elements are the same, then continue (skip the elements as these two elements are duplicates).

Step 6: If the difference between the current and previous element is 1, then increment the count of the longest consecutive subsequence and update the max_length to the maximum by comparing it with the count.

Step 7: Else set the count to 1, as the length of the longest consecutive subsequence is broken. So we need to start with 1 from the next element.

Step 8: Return the max_length, as this will store the length of the longest consecutive subsequence.

Let's look at the implementation of the above-explained approach with code implementation:

  • C++
  • Java
  • Python
  • C#
  • Javascript

C++

#include <bits/stdc++.h>
using namespace std;

int longestConsecutive(vector<int> & nums) {
int n = nums.size();

// if n is 0, return 0 as the length of longest consecutive will be 0.
if (n == 0) return 0;

// create a min heap where the minimum element will have the highest prioriy.
priority_queue <int, vector <int>, greater <int>> pq;

/* create two variables, to maintain the count and the maximum length of longest consecutive subsequence */
int count = 1, max_length = 1;

/* start an iteration from 0 to n, and push the elements in priority queue. */
for (int i = 0; i < n; i++)
pq.push(nums[i]);

// start an iteration till the priority queue gets empty.
while (!pq.empty()) {

// retrieve the minimum element using top() method.
int x = pq.top();

// remove this minimum element from priority queue using pop() method.
pq.pop();

/* now if the difference betweent the current minimum (top of pq) and x is 1, then increment the count. */
if (pq.top() - x == 1)
count++;

// if both the elements are the same, skip.
else if (x == pq.top())
continue;

// else set the count to 1 and start with 1 from the next element.
else
count = 1;

// update the max_length with the maximum length.
max_length = max(max_length, count);
}

return max_length;
}

int main() {
vector <int> input = { 33, 20, 34, 30, 35 };
cout << "Length of Longest Consecutive Subsequence is " << longestConsecutive(input);
return 0;
}
You can also try this code with Online C++ Compiler
Run Code

Java

import java.util.PriorityQueue;
import java.util.List;

public class Main {
public static int longestConsecutive(List<Integer> nums) {
int n = nums.size();
if (n == 0) return 0;

PriorityQueue<Integer> pq = new PriorityQueue<>();

for (int num : nums) {
pq.add(num);
}

int count = 1, max_length = 1;

int prev = pq.poll();
while (!pq.isEmpty()) {
int current = pq.poll();

if (current - prev == 1) {
count++;
} else if (prev != current) {
count = 1;
}
max_length = Math.max(max_length, count);
prev = current;
}

return max_length;
}

public static void main(String[] args) {
List<Integer> input = List.of(33, 20, 34, 30, 35);
System.out.println("Length of Longest Consecutive Subsequence is " + longestConsecutive(input));
}
}
You can also try this code with Online Java Compiler
Run Code

Python

import heapq

def longestConsecutive(nums):
n = len(nums)
if n == 0:
return 0

heapq.heapify(nums)

count = 1
max_length = 1

prev = heapq.heappop(nums)
while nums:
current = heapq.heappop(nums)
if current - prev == 1:
count += 1
elif current != prev:
count = 1
max_length = max(max_length, count)
prev = current

return max_length

input = [33, 20, 34, 30, 35]
print("Length of Longest Consecutive Subsequence is", longestConsecutive(input))
You can also try this code with Online Python Compiler
Run Code

C#

using System;
using System.Collections.Generic;

class Program {
public static int LongestConsecutive(List<int> nums) {
int n = nums.Count;
if (n == 0) return 0;

PriorityQueue<int, int> pq = new PriorityQueue<int, int>();

foreach (int num in nums) {
pq.Enqueue(num, num);
}

int count = 1, max_length = 1;

int prev = pq.Dequeue();
while (pq.Count > 0) {
int current = pq.Dequeue();
if (current - prev == 1) {
count++;
} else if (prev != current) {
count = 1;
}
max_length = Math.Max(max_length, count);
prev = current;
}

return max_length;
}

static void Main() {
List<int> input = new List<int> {33, 20, 34, 30, 35};
Console.WriteLine("Length of Longest Consecutive Subsequence is " + LongestConsecutive(input));
}
}

Javascript

function longestConsecutive(nums) {
if (nums.length === 0) return 0;

nums.sort((a, b) => a - b);

let count = 1, max_length = 1;

let prev = nums[0];
for (let i = 1; i < nums.length; i++) {
if (nums[i] - prev === 1) {
count++;
} else if (nums[i] !== prev) {
count = 1;
}
max_length = Math.max(max_length, count);
prev = nums[i];
}

return max_length;
}

const input = [33, 20, 34, 30, 35];
console.log("Length of Longest Consecutive Subsequence is " + longestConsecutive(input));
You can also try this code with Online Javascript Compiler
Run Code

Output:

Longest Consecutive Subsequence using Priority Queue - Output

Longest Consecutive Subsequence using Dynamic Programming:

In this approach, we will use dynamic programming method to find the length of longest consecutive subsequence. Here are the following steps to understand this approach:

Step 1: Create a map of <int, int> and this map will be considered as the Dynamic Programming array that stores the solutions.

Step 2: Iteration will be made from 0 to n and initially for every element, we will store 1 as the count in the seq (DP array).

Step 3: One more iteration will be made from 0 to n, where the max_length will be updated with value given by the populateSeq function. Now let's move in to the populateSeq function.

Step 4: If the current element's solution is not present in seq, return 0.

Step 5: Else If the solution is present, return 1.

Step 6: Else find the solution for the element + 1. Add the found solution in current's solution.

Step 7: Return the solution for current element.

Let's look at the implementation of the above-explained approach with code implementation:

  • C++
  • Java
  • Python
  • C#
  • Javascript

C++

#include <bits/stdc++.h>
using namespace std;

/* seq is the map that we are using as a dp array, to use it in overlapping situations */
unordered_map<int, int> seq;
int populateSeq(int x) {

/* if the current element's solution is not present in seq, return 0. */
if (seq.find(x) == seq.end())
return 0;
// if the solution is present, return it.
if (seq[x] != 1)
return seq[x];

// else find the solution for the element + 1
int p = populateSeq(x + 1);

// add the found solution in current's solution.
seq[x] += p;

return seq[x];
}
int longestConsecutive(vector<int> & nums) {
int n = nums.size(), max_length = 0;

// initially, assign all the elements with count 1.
for (int i = 0; i < n; i++)
seq[nums[i]] = 1;

// iterate 0 to n and find the maximum solution for each element.
for (int i = 0; i < n; i++)
max_length = max(max_length, populateSeq(nums[i]));

return max_length;
}
int main() {
vector<int> input = { 33, 20, 34, 30, 35 };
cout << "Length of Longest Consecutive Subsequence is " << longestConsecutive(input);
return 0;
}
You can also try this code with Online C++ Compiler
Run Code

Java

import java.util.HashMap;
import java.util.Map;

public class Main {
private static Map<Integer, Integer> seq = new HashMap<>();

private static int populateSeq(int x) {
if (!seq.containsKey(x))
return 0;
if (seq.get(x) != 1)
return seq.get(x);

int p = populateSeq(x + 1);
seq.put(x, seq.get(x) + p);

return seq.get(x);
}

public static int longestConsecutive(int[] nums) {
int n = nums.length, max_length = 0;

for (int num : nums)
seq.put(num, 1);

for (int num : nums)
max_length = Math.max(max_length, populateSeq(num));

return max_length;
}

public static void main(String[] args) {
int[] input = {33, 20, 34, 30, 35};
System.out.println("Length of Longest Consecutive Subsequence is " + longestConsecutive(input));
}
}
You can also try this code with Online Java Compiler
Run Code

Python

seq = {}

def populateSeq(x):
if x not in seq:
return 0
if seq[x] != 1:
return seq[x]

p = populateSeq(x + 1)
seq[x] += p

return seq[x]

def longestConsecutive(nums):
max_length = 0

for num in nums:
seq[num] = 1

for num in nums:
max_length = max(max_length, populateSeq(num))

return max_length

input = [33, 20, 34, 30, 35]
print("Length of Longest Consecutive Subsequence is", longestConsecutive(input))
You can also try this code with Online Python Compiler
Run Code

C#

using System;
using System.Collections.Generic;

class Program {
private static Dictionary<int, int> seq = new Dictionary<int, int>();

private static int PopulateSeq(int x) {
if (!seq.ContainsKey(x))
return 0;
if (seq[x] != 1)
return seq[x];

int p = PopulateSeq(x + 1);
seq[x] += p;

return seq[x];
}

public static int LongestConsecutive(int[] nums) {
int max_length = 0;

foreach (int num in nums)
seq[num] = 1;

foreach (int num in nums)
max_length = Math.Max(max_length, PopulateSeq(num));

return max_length;
}

static void Main() {
int[] input = {33, 20, 34, 30, 35};
Console.WriteLine("Length of Longest Consecutive Subsequence is " + LongestConsecutive(input));
}
}

Javascript

let seq = {};

function populateSeq(x) {
if (!(x in seq))
return 0;
if (seq[x] !== 1)
return seq[x];

let p = populateSeq(x + 1);
seq[x] += p;

return seq[x];
}

function longestConsecutive(nums) {
let max_length = 0;

nums.forEach(num => {
seq[num] = 1;
});

nums.forEach(num => {
max_length = Math.max(max_length, populateSeq(num));
});

return max_length;
}

const input = [33, 20, 34, 30, 35];
console.log("Length of Longest Consecutive Subsequence is " + longestConsecutive(input));
You can also try this code with Online Javascript Compiler
Run Code


Output:

Longest Consecutive Subsequence using Dynamic Programming - Output

Longest Consecutive Subsequence using Hashing:

Step 1: Store all the elements of the array in a hash set.
Step 2: Iterate through each element of the array.
Step 3: For each element, check if it's the start of a sequence (i.e., check if element - 1 is not in the hash set).
Step 4: If it's the start, count the number of consecutive elements present in the hash set starting from this element.
Step 5: Keep track of the maximum length of such consecutive sequences.
Step 6: Return the maximum length.

  • C++
  • Java
  • Python
  • C#
  • Javascript

C++

#include <iostream>
#include <unordered_set>
#include <vector>
using namespace std;
int findLongestConseqSubseq(vector<int>& arr) {
unordered_set<int> S;
int ans = 0;
// Hash all the array elements
for (int i = 0; i < arr.size(); i++) {
S.insert(arr[i]);
}
// Check each possible sequence from the start
for (int i = 0; i < arr.size(); i++) {
if (S.find(arr[i] - 1) == S.end()) {
int j = arr[i];
while (S.find(j) != S.end()) {
j++;
}
// Update optimal length
ans = max(ans, j - arr[i]);
}
}
return ans;
}
int main() {
vector<int> arr = {1, 9, 3, 10, 4, 20, 2};
cout << "Length of the Longest consecutive subsequence is "
<< findLongestConseqSubseq(arr) << endl;
return 0;
}
You can also try this code with Online C++ Compiler
Run Code

Java

import java.util.HashSet;
import java.util.Set;

public class Main {
public static int findLongestConseqSubseq(int[] arr) {
Set<Integer> S = new HashSet<>();
int ans = 0;

for (int num : arr) {
S.add(num);
}

for (int num : arr) {
if (!S.contains(num - 1)) {
int j = num;
while (S.contains(j)) {
j++;
}
ans = Math.max(ans, j - num);
}
}
return ans;
}

public static void main(String[] args) {
int[] arr = {1, 9, 3, 10, 4, 20, 2};
System.out.println("Length of the Longest consecutive subsequence is " + findLongestConseqSubseq(arr));
}
}
You can also try this code with Online Java Compiler
Run Code

Python

def findLongestConseqSubseq(arr):
S = set(arr)
ans = 0

for num in arr:
if num - 1 not in S:
j = num
while j in S:
j += 1
ans = max(ans, j - num)
return ans

arr = [1, 9, 3, 10, 4, 20, 2]
print("Length of the Longest consecutive subsequence is", findLongestConseqSubseq(arr))
You can also try this code with Online Python Compiler
Run Code

C#

using System;
using System.Collections.Generic;

class Program {
public static int FindLongestConseqSubseq(int[] arr) {
HashSet<int> S = new HashSet<int>();
int ans = 0;

foreach (int num in arr) {
S.Add(num);
}

foreach (int num in arr) {
if (!S.Contains(num - 1)) {
int j = num;
while (S.Contains(j)) {
j++;
}
ans = Math.Max(ans, j - num);
}
}
return ans;
}

static void Main() {
int[] arr = {1, 9, 3, 10, 4, 20, 2};
Console.WriteLine("Length of the Longest consecutive subsequence is " + FindLongestConseqSubseq(arr));
}
}

Javascript

function findLongestConseqSubseq(arr) {
const S = new Set(arr);
let ans = 0;

arr.forEach(num => {
if (!S.has(num - 1)) {
let j = num;
while (S.has(j)) {
j++;
}
ans = Math.max(ans, j - num);
}
});
return ans;
}

const arr = [1, 9, 3, 10, 4, 20, 2];
console.log("Length of the Longest consecutive subsequence is " + findLongestConseqSubseq(arr));
You can also try this code with Online Javascript Compiler
Run Code

:

Output:

Length of the Longest consecutive subsequence is 4

Check out this : Longest common subsequence

Frequently Asked Questions

Can I find the longest consecutive subsequence of an array without sorting the array?

Yes, you can accomplish this by the second method discussed in this blog, i.e., using hashing.

How does the longest common sequence work?

In a given sorted array, numbers are 2, 3, 4, and 5. Here the difference between the 2 consecutive numbers is 1 then there is a common sequence and if there are more than 2 elements, then we can find the longest common sequence.

Can there be more than one longest common subsequence?

Yes there can multiple common subsequence in the array but in the context of problem, we consider only the length of the longest common subsequence.

How do you find the longest consecutive sequence in an array?

To find the longest consecutive sequence in an array, you can iterate through the array, keeping track of the current sequence length and the maximum sequence length encountered so far.

Which is known to be the longest sequence or path?

In various contexts, the longest sequence or path refers to the sequence or path within a dataset, graph, or other structures that has the greatest number of elements or vertices between its starting and ending points.

Conclusion

In this blog, we have discussed the longest consecutive sequence problem. Understanding and implementing algorithms to find the longest consecutive sequence in an array offers valuable insights into efficient problem-solving techniques. By employing strategies such as sorting, hashing, or utilizing sets, programmers can tackle diverse scenarios with varying complexities.

Brute force was taking O(N*logN) complexity that’s why we optimized that code to decrease its time complexity. 

Recommended Problems - 

Do check out The Interview guide for Product Based Companies as well as some of the Popular Interview Problems from Top companies like AmazonAdobeGoogleUberMicrosoft, etc. 

Also check out our Guided PathsContests, Test Series, and some Interview Experiences curated by top Industry Experts only on Code 360.

Live masterclass