# Longest Consecutive Subsequence

Given an array of integers, 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[] = {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:

The idea is to first sort the array and find the longest subarray with consecutive elements. After sorting the array and removing the multiple occurrences of elements, run a loop and keep a count and max (both initially zero). Run a loop from start to end and if the current element is not equal to the previous (element+1) then set the count to 1 else increase the count. Update max with a maximum of count and max.

Illustration:

Input: arr[] = {1, 9, 3, 10, 4, 20, 2}

First sort the array to arrange them in a consecutive fashion.
arr[] = {1, 2, 3, 4, 9, 10, 20}

Now, store the distinct elements from the sorted array.
dist[] = {1, 2, 3, 4, 9, 10, 20}

Initialize countConsecutive with 0 which will increment when arr[i] == arr[i – 1] + 1 is true otherwise countConsecutive will re-initialize by 1.

Maintain a variable ans to store the maximum count of consecutive elements so far.

At i = 0:

• as i is 0 then re-initialize countConsecutive by 1.
• ans = max(ans, countConsecutive) = max(0, 1) = 1

At i = 1:

• check if (dist == dist + 1) = (2 == 1 + 1) = true
• as the above condition is true, therefore increment countConsecutive by 1
• countConsecutive = countConsecutive + 1 = 1 + 1 = 2
• ans = max(ans, countConsecutive) = max(1, 2) = 1

At i = 2:

• check if (dist == dist + 1) = (3 == 2 + 1) = true
• as the above condition is true, therefore increment countConsecutive by 1
• countConsecutive = countConsecutive + 1 = 2 + 1 = 3
• ans = max(ans, countConsecutive) = max(2, 3) = 3

At i = 3:

• check if (dist == dist + 1) = (4 == 3 + 1) = true
• as the above condition is true, therefore increment countConsecutive by 1
• countConsecutive = countConsecutive + 1 = 3 + 1 = 4
• ans = max(ans, countConsecutive) = max(3, 4) = 4

At i = 4:

• check if (dist == dist + 1) = (9 != 4 + 1) = false
• as the above condition is false, therefore re-initialize countConsecutive by 1
• countConsecutive = 1
• ans = max(ans, countConsecutive) = max(4, 1) = 4

At i = 5:

• check if (dist == dist + 1) = (10 == 9 + 1) = true
• as the above condition is true, therefore increment countConsecutive by 1
• countConsecutive = countConsecutive + 1 = 1 + 1 = 2
• ans = max(ans, countConsecutive) = max(4, 2) = 4

At i = 6:

• check if (dist == dist + 1) = (20 != 10 + 1) = false
• as the above condition is false, therefore re-initialize countConsecutive by 1
• countConsecutive = 1
• ans = max(ans, countConsecutive) = max(4, 1) = 4

Therefore the longest consecutive subsequence is {1, 2, 3, 4}
Hence, ans is 4.

Follow the steps below to solve the problem:

• Initialize ans and countConsecutive with 0.
• Sort the arr[].
• Store the distinct elements in dist[] array by traversing over the arr[].
• Now, traverse on the dist[] array to find the count of consecutive elements.
• Simultaneously maintain the answer variable.

Below is the implementation of the above approach:

## C++

 `// C++ program to find longest` `// contiguous subsequence` `#include ` `using` `namespace` `std;`   `// Returns length of the longest` `// contiguous subsequence` `int` `findLongestConseqSubseq(``int` `arr[], ``int` `n)` `{` `    ``int` `ans = 0, count = 0;`   `    ``// sort the array` `    ``sort(arr, arr + n);`   `    ``vector<``int``> v;` `    ``v.push_back(arr);`   `    ``// insert repeated elements only once in the vector` `    ``for` `(``int` `i = 1; i < n; i++) {` `        ``if` `(arr[i] != arr[i - 1])` `            ``v.push_back(arr[i]);` `    ``}` `    ``// find the maximum length` `    ``// by traversing the array` `    ``for` `(``int` `i = 0; i < v.size(); i++) {`   `        ``// Check if the current element is equal` `        ``// to previous element +1` `        ``if` `(i > 0 && v[i] == v[i - 1] + 1)` `            ``count++;` `        ``// reset the count` `        ``else` `            ``count = 1;`   `        ``// update the maximum` `        ``ans = max(ans, count);` `    ``}` `    ``return` `ans;` `}`   `// Driver code` `int` `main()` `{` `    ``int` `arr[] = { 1, 2, 2, 3 };` `    ``int` `n = ``sizeof` `arr / ``sizeof` `arr;` `    ``cout << ``"Length of the Longest contiguous subsequence "` `            ``"is "` `         ``<< findLongestConseqSubseq(arr, n);` `    ``return` `0;` `}`

## Java

 `// Java program to find longest` `// contiguous subsequence` `import` `java.io.*;` `import` `java.util.*;`   `class` `GFG {`   `    ``static` `int` `findLongestConseqSubseq(``int` `arr[], ``int` `n)` `    ``{`   `        ``// Sort the array` `        ``Arrays.sort(arr);`   `        ``int` `ans = ``0``, count = ``0``;`   `        ``ArrayList v = ``new` `ArrayList();` `        ``v.add(arr[``0``]);`   `        ``// Insert repeated elements` `        ``// only once in the vector` `        ``for` `(``int` `i = ``1``; i < n; i++) {` `            ``if` `(arr[i] != arr[i - ``1``])` `                ``v.add(arr[i]);` `        ``}`   `        ``// Find the maximum length` `        ``// by traversing the array` `        ``for` `(``int` `i = ``0``; i < v.size(); i++) {`   `            ``// Check if the current element is` `            ``// equal to previous element +1` `            ``if` `(i > ``0` `&& v.get(i) == v.get(i - ``1``) + ``1``)` `                ``count++;` `            ``else` `                ``count = ``1``;`   `            ``// Update the maximum` `            ``ans = Math.max(ans, count);` `        ``}` `        ``return` `ans;` `    ``}`   `    ``// Driver code` `    ``public` `static` `void` `main(String[] args)` `    ``{` `        ``int` `arr[] = { ``1``, ``9``, ``3``, ``10``, ``4``, ``20``, ``2` `};` `        ``int` `n = arr.length;`   `        ``System.out.println(` `            ``"Length of the Longest "` `            ``+ ``"contiguous subsequence is "` `            ``+ findLongestConseqSubseq(arr, n));` `    ``}` `}`   `// This code is contributed by parascoding`

## Python3

 `# Python3 program to find longest` `# contiguous subsequence`   `# Returns length of the longest` `# contiguous subsequence`     `def` `findLongestConseqSubseq(arr, n):`   `    ``ans ``=` `0` `    ``count ``=` `0`   `    ``# Sort the array` `    ``arr.sort()`   `    ``v ``=` `[]`   `    ``v.append(arr[``0``])`   `    ``# Insert repeated elements only` `    ``# once in the vector` `    ``for` `i ``in` `range``(``1``, n):` `        ``if` `(arr[i] !``=` `arr[i ``-` `1``]):` `            ``v.append(arr[i])`   `    ``# Find the maximum length` `    ``# by traversing the array` `    ``for` `i ``in` `range``(``len``(v)):`   `        ``# Check if the current element is` `        ``# equal to previous element +1` `        ``if` `(i > ``0` `and` `v[i] ``=``=` `v[i ``-` `1``] ``+` `1``):` `            ``count ``+``=` `1`   `        ``# Reset the count` `        ``else``:` `            ``count ``=` `1`   `        ``# Update the maximum` `        ``ans ``=` `max``(ans, count)`   `    ``return` `ans`     `# Driver code` `arr ``=` `[``1``, ``2``, ``2``, ``3``]` `n ``=` `len``(arr)`   `print``(``"Length of the Longest contiguous subsequence is"``,` `      ``findLongestConseqSubseq(arr, n))`   `# This code is contributed by avanitrachhadiya2155`

## C#

 `// C# program to find longest` `// contiguous subsequence` `using` `System;` `using` `System.Collections.Generic;`   `class` `GFG {`   `    ``static` `int` `findLongestConseqSubseq(``int``[] arr, ``int` `n)` `    ``{`   `        ``// Sort the array` `        ``Array.Sort(arr);`   `        ``int` `ans = 0, count = 0;`   `        ``List<``int``> v = ``new` `List<``int``>();` `        ``v.Add(10);`   `        ``// Insert repeated elements` `        ``// only once in the vector` `        ``for` `(``int` `i = 1; i < n; i++) {` `            ``if` `(arr[i] != arr[i - 1])` `                ``v.Add(arr[i]);` `        ``}`   `        ``// Find the maximum length` `        ``// by traversing the array` `        ``for` `(``int` `i = 0; i < v.Count; i++) {`   `            ``// Check if the current element is` `            ``// equal to previous element +1` `            ``if` `(i > 0 && v[i] == v[i - 1] + 1)` `                ``count++;` `            ``else` `                ``count = 1;`   `            ``// Update the maximum` `            ``ans = Math.Max(ans, count);` `        ``}` `        ``return` `ans;` `    ``}`   `    ``// Driver code` `    ``static` `void` `Main()` `    ``{` `        ``int``[] arr = { 1, 9, 3, 10, 4, 20, 2 };` `        ``int` `n = arr.Length;`   `        ``Console.WriteLine(` `            ``"Length of the Longest "` `            ``+ ``"contiguous subsequence is "` `            ``+ findLongestConseqSubseq(arr, n));` `    ``}` `}`   `// This code is contributed by divyeshrabadiya07`

## Javascript

 ``

Output

```Length of the Longest contiguous subsequence is 3

```

Time complexity: O(Nlog(N)), Time to sort the array is O(Nlog(N)).
Auxiliary space: O(N). Extra space is needed for storing distinct elements.

## Longest Consecutive Subsequence using sorting without removing duplicate elements:

The approach involves initially sorting the array. Next, you count the consecutive elements present in the sorted array while skipping any repeated elements.

Below is the implementation:

## C++

 `// C++ program to find longest` `// contiguous subsequence` `#include ` `#include `   `int` `main()` `{` `    ``int` `arr[] = {0, 1, 1, 1, 1, 1, 2, 3};` `    ``int` `N = ``sizeof``(arr) / ``sizeof``(arr);`   `    ``// If the array has only one element, the longest consecutive subsequence is 1` `    ``if` `(N == 1)` `    ``{` `        ``std::cout << ``"Longest Consecutive subsequence: 1"` `<< std::endl;` `        ``return` `0;` `    ``}`   `    ``std::sort(arr, arr + N); ``// Sort the array in ascending order`   `    ``int` `count = 1;` `    ``int` `max_count = -1;`   `    ``for` `(``int` `i = 0; i < N - 1; i++)` `    ``{` `        ``// Check if the difference between the current element and the next element is 1` `        ``if` `(arr[i + 1] - arr[i] == 1)` `        ``{` `            ``count++;` `        ``}` `        ``// If the difference is 0, continue to the next iteration` `        ``else` `if` `(arr[i + 1] - arr[i] == 0)` `        ``{` `            ``continue``;` `        ``}` `        ``// If the difference is not 1 or 0, reset the count to 1` `        ``else` `        ``{` `            ``count = 1;` `        ``}`   `        ``// Update max_count with the maximum value between max_count and count` `        ``max_count = std::max(max_count, count);` `    ``}`   `    ``std::cout << ``"Longest Consecutive subsequence: "` `<< max_count << std::endl;`   `    ``return` `0;` `}`

## Java

 `import` `java.util.*;`   `class` `GFG {` `    ``public` `static` `void` `main(String args[])` `    ``{` `      ``int` `arr[] = {``0``,``1``,``1``,``1``,``1``,``1``,``2``,``3``};` `      ``int` `N = arr.length;` `      `  `      ``if``(N == ``1``){` `        ``System.out.println(``"Longest Consecutive subsequence: 1"``);` `          ``return``;` `      ``}` `      `  `        ``Arrays.sort(arr);` `        ``int` `count = ``1``;` `        ``int` `max_count = -``1``;` `        ``for``(``int` `i=``0``; i < N-``1``; i++)` `        ``{` `            ``if``(arr[i+``1``] - arr[i] == ``1``)` `            ``{` `                ``count++;` `            ``}` `            ``else` `if``(arr[i+``1``] - arr[i] == ``0``)` `            ``{` `                ``continue``;` `            ``}` `            ``else` `            ``{` `                ``count = ``1``;` `            ``}` `            ``max_count = Math.max(max_count, count);` `        ``}` `      ``System.out.println(``"Longest Consecutive subsequence: "``+max_count);` `    ``}` `}`

## Python

 `def` `find_longest_contiguous_subsequence(arr):` `    ``arr.sort()  ``# Sort the array in ascending order` `    ``n ``=` `len``(arr)`   `    ``# If the array has only one element, the longest consecutive subsequence is 1` `    ``if` `n ``=``=` `1``:` `        ``return` `1`   `    ``count ``=` `1` `    ``max_count ``=` `-``1`   `    ``for` `i ``in` `range``(n ``-` `1``):` `        ``# Check if the difference between the current element and the next element is 1` `        ``if` `arr[i ``+` `1``] ``-` `arr[i] ``=``=` `1``:` `            ``count ``+``=` `1` `        ``# If the difference is 0, continue to the next iteration` `        ``elif` `arr[i ``+` `1``] ``-` `arr[i] ``=``=` `0``:` `            ``continue` `        ``# If the difference is not 1 or 0, reset the count to 1` `        ``else``:` `            ``count ``=` `1`   `        ``# Update max_count with the maximum value between max_count and count` `        ``max_count ``=` `max``(max_count, count)`   `    ``return` `max_count`   `arr ``=` `[``0``, ``1``, ``1``, ``1``, ``1``, ``1``, ``2``, ``3``]` `result ``=` `find_longest_contiguous_subsequence(arr)` `print``(``"Longest Consecutive subsequence:"``, result)`

## C#

 `using` `System;` `using` `System.Linq;`   `namespace` `LongestConsecutiveSubsequence` `{` `    ``class` `Program` `    ``{` `        ``static` `void` `Main(``string``[] args)` `        ``{` `            ``int``[] arr = { 0, 1, 1, 1, 1, 1, 2, 3 };` `            ``int` `N = arr.Length;`   `            ``// If the array has only one element, the longest consecutive subsequence is 1` `            ``if` `(N == 1)` `            ``{` `                ``Console.WriteLine(``"Longest Consecutive subsequence: 1"``);` `                ``return``;` `            ``}`   `            ``Array.Sort(arr); ``// Sort the array in ascending order`   `            ``int` `count = 1;` `            ``int` `maxCount = -1;`   `            ``for` `(``int` `i = 0; i < N - 1; i++)` `            ``{` `                ``// Check if the difference between the current element and the next element is 1` `                ``if` `(arr[i + 1] - arr[i] == 1)` `                ``{` `                    ``count++;` `                ``}` `                ``// If the difference is 0, continue to the next iteration` `                ``else` `if` `(arr[i + 1] - arr[i] == 0)` `                ``{` `                    ``continue``;` `                ``}` `                ``// If the difference is not 1 or 0, reset the count to 1` `                ``else` `                ``{` `                    ``count = 1;` `                ``}`   `                ``// Update maxCount with the maximum value between maxCount and count` `                ``maxCount = Math.Max(maxCount, count);` `            ``}`   `            ``Console.WriteLine(\$``"Longest Consecutive subsequence: {maxCount}"``);` `        ``}` `    ``}` `}`

## Javascript

 `function` `findLongestConsecutiveSubsequence(arr) {` `    ``let N = arr.length;`   `    ``// If the array has only one element, the longest consecutive subsequence is 1` `    ``if` `(N === 1) {` `        ``console.log(``"Longest Consecutive subsequence: 1"``);` `        ``return``;` `    ``}`   `    ``arr.sort((a, b) => a - b); ``// Sort the array in ascending order`   `    ``let count = 1;` `    ``let max_count = -1;`   `    ``for` `(let i = 0; i < N - 1; i++) {` `        ``// Check if the difference between the current element and the next element is 1` `        ``if` `(arr[i + 1] - arr[i] === 1) {` `            ``count++;` `        ``}` `        ``// If the difference is 0, continue to the next iteration` `        ``else` `if` `(arr[i + 1] - arr[i] === 0) {` `            ``continue``;` `        ``}` `        ``// If the difference is not 1 or 0, reset the count to 1` `        ``else` `{` `            ``count = 1;` `        ``}`   `        ``// Update max_count with the maximum value between max_count and count` `        ``max_count = Math.max(max_count, count);` `    ``}`   `    ``console.log(``"Longest Consecutive subsequence: "` `+ max_count);` `}`   `// Test` `let arr = [0, 1, 1, 1, 1, 1, 2, 3];` `findLongestConsecutiveSubsequence(arr);`

Output

```Longest Consecutive subsequence: 4

```

Time Complexity: O(NlogN): Due to the sorting step, while the subsequent traversal of the sorted array only requires O(N) time.
Space Complexity: O(1): No extra space is being used.

## Longest Consecutive Subsequence using Hashing:

The idea is to use Hashing. We first insert all elements in a Set. Then check all the possible starts of consecutive subsequences.

Illustration:

Below image is the dry run, for example, arr[] = {1, 9, 3, 10, 4, 20, 2}: Follow the steps below to solve the problem:

• Create an empty hash.
• Insert all array elements to hash.
• Do the following for every element arr[i]
• Check if this element is the starting point of a subsequence. To check this, simply look for arr[i] – 1 in the hash, if not found, then this is the first element of a subsequence.
• If this element is the first element, then count the number of elements in the consecutive starting with this element. Iterate from arr[i] + 1 till the last element that can be found.
• If the count is more than the previous longest subsequence found, then update this.

Below is the implementation of the above approach:

## C++

 `// C++ program to find longest` `// contiguous subsequence` `#include ` `using` `namespace` `std;`   `// Returns length of the longest` `// contiguous subsequence` `int` `findLongestConseqSubseq(``int` `arr[], ``int` `n)` `{` `    ``unordered_set<``int``> S;` `    ``int` `ans = 0;`   `    ``// Hash all the array elements` `    ``for` `(``int` `i = 0; i < n; i++)` `        ``S.insert(arr[i]);`   `    ``// check each possible sequence from` `    ``// the start then update optimal length` `    ``for` `(``int` `i = 0; i < n; i++) {` `        ``// Check if the previous number (arr[i] - 1) is` `        ``// present in the set,` `        ``// if it is then that number (arr[i]) is not the` `        ``// starting of the sequence.` `        ``if` `(S.find(arr[i] - 1) != S.end()) {` `            ``continue``;` `        ``}` `        ``else` `{` `            ``// If previous number is not present, that means` `            ``// that number is the starting of the sequence.` `            ``int` `j = arr[i];` `            ``while` `(S.find(j) != S.end())` `                ``j++;`   `            ``// update optimal length if` `            ``// this length is more` `            ``ans = max(ans, j - arr[i]);` `        ``}` `    ``}` `    ``return` `ans;` `}`   `// Driver code` `int` `main()` `{` `    ``int` `arr[] = { 1, 9, 3, 10, 4, 20, 2 };` `    ``int` `n = ``sizeof` `arr / ``sizeof` `arr;` `    ``cout << ``"Length of the Longest contiguous subsequence "` `            ``"is "` `         ``<< findLongestConseqSubseq(arr, n);` `    ``return` `0;` `}`

## Java

 `// Java program to find longest` `// consecutive subsequence` `import` `java.io.*;` `import` `java.util.*;`   `class` `ArrayElements {` `    ``// Returns length of the longest` `    ``// consecutive subsequence` `    ``static` `int` `findLongestConseqSubseq(``int` `arr[], ``int` `n)` `    ``{` `        ``HashSet S = ``new` `HashSet();` `        ``int` `ans = ``0``;`   `        ``// Hash all the array elements` `        ``for` `(``int` `i = ``0``; i < n; ++i)` `            ``S.add(arr[i]);`   `        ``// check each possible sequence from the start` `        ``// then update optimal length` `        ``for` `(``int` `i = ``0``; i < n; ++i) {` `            ``// if current element is the starting` `            ``// element of a sequence` `            ``if` `(!S.contains(arr[i] - ``1``)) {` `                ``// Then check for next elements` `                ``// in the sequence` `                ``int` `j = arr[i];` `                ``while` `(S.contains(j)){` `                      ``S.remove(Integer.valueOf(j));``//this will improve runtime by avoiding the repetitive counts of elements ` `                    ``j++;` `                    ``}`   `                ``// update  optimal length if this` `                ``// length is more` `                ``if` `(ans < j - arr[i])` `                    ``ans = j - arr[i];` `            ``}` `        ``}` `        ``return` `ans;` `    ``}`   `    ``// Driver Code` `    ``public` `static` `void` `main(String args[])` `    ``{` `        ``int` `arr[] = { ``1``, ``9``, ``3``, ``10``, ``4``, ``20``, ``2` `};` `        ``int` `n = arr.length;` `        ``System.out.println(` `            ``"Length of the Longest consecutive subsequence is "` `            ``+ findLongestConseqSubseq(arr, n));` `    ``}` `}` `// This code is contributed by Aakash Hasija`

## Python3

 `# Python program to find longest contiguous subsequence`     `def` `findLongestConseqSubseq(arr, n):`   `    ``s ``=` `set``()` `    ``ans ``=` `0`   `    ``# Hash all the array elements` `    ``for` `ele ``in` `arr:` `        ``s.add(ele)`   `    ``# check each possible sequence from the start` `    ``# then update optimal length` `    ``for` `i ``in` `range``(n):`   `         ``# if current element is the starting` `        ``# element of a sequence` `        ``if` `(arr[i]``-``1``) ``not` `in` `s:`   `            ``# Then check for next elements in the` `            ``# sequence` `            ``j ``=` `arr[i]` `            ``while``(j ``in` `s):` `                ``j ``+``=` `1`   `            ``# update  optimal length if this length` `            ``# is more` `            ``ans ``=` `max``(ans, j``-``arr[i])` `    ``return` `ans`     `# Driver code` `if` `__name__ ``=``=` `'__main__'``:` `    ``n ``=` `7` `    ``arr ``=` `[``1``, ``9``, ``3``, ``10``, ``4``, ``20``, ``2``]` `    ``print``(``"Length of the Longest contiguous subsequence is "``,` `          ``findLongestConseqSubseq(arr, n))`   `# Contributed by: Harshit Sidhwa`

## C#

 `using` `System;` `using` `System.Collections.Generic;`   `// C# program to find longest consecutive subsequence`   `public` `class` `ArrayElements {` `    ``// Returns length of the` `    ``// longest consecutive subsequence` `    ``public` `static` `int` `findLongestConseqSubseq(``int``[] arr,` `                                              ``int` `n)` `    ``{` `        ``HashSet<``int``> S = ``new` `HashSet<``int``>();` `        ``int` `ans = 0;`   `        ``// Hash all the array elements` `        ``for` `(``int` `i = 0; i < n; ++i) {` `            ``S.Add(arr[i]);` `        ``}`   `        ``// check each possible sequence from the start` `        ``// then update optimal length` `        ``for` `(``int` `i = 0; i < n; ++i) {` `            ``// if current element is the starting` `            ``// element of a sequence` `            ``if` `(!S.Contains(arr[i] - 1)) {` `                ``// Then check for next elements in the` `                ``// sequence` `                ``int` `j = arr[i];` `                ``while` `(S.Contains(j)) {` `                    ``j++;` `                ``}`   `                ``// update  optimal length if this length` `                ``// is more` `                ``if` `(ans < j - arr[i]) {` `                    ``ans = j - arr[i];` `                ``}` `            ``}` `        ``}` `        ``return` `ans;` `    ``}`   `    ``// Driver code` `    ``public` `static` `void` `Main(``string``[] args)` `    ``{` `        ``int``[] arr = ``new` `int``[] { 1, 9, 3, 10, 4, 20, 2 };` `        ``int` `n = arr.Length;` `        ``Console.WriteLine(` `            ``"Length of the Longest consecutive subsequence is "` `            ``+ findLongestConseqSubseq(arr, n));` `    ``}` `}`   `// This code is contributed by Shrikant13`

## Javascript

 ``

Output

```Length of the Longest contiguous subsequence is 4

```

Time complexity: O(N), Only one traversal is needed and the time complexity is O(n) under the assumption that hash insert and search takes O(1) time.
Auxiliary space: O(N), To store every element in the hashmap O(n) space is needed

## Longest Consecutive Subsequence using Priority Queue:

The Idea is to use Priority Queue. Using priority queue it will sort the elements and eventually it will help to find consecutive elements.

Illustration:

Input: arr[] = {1, 9, 3, 10, 4, 20, 2}

Insert all the elements in the Priority Queue:

 1 2 3 4 9 10 20

Initialise variable prev with first element of priority queue, prev will contain last element has been picked and it will help to check whether the current element is contributing for consecutive sequence or not.

prev = 1, countConsecutive = 1, ans = 1

Run the algorithm till the priority queue becomes empty.

 2 3 4 9 10 20
• current element is 2
• prev + 1 == 2, therefore increment countConsecutive by 1
• countConsecutive = countConsecutive + 1 = 1 + 1 = 2
• update prev with current element, prev = 2
• pop the current element
• ans = max(ans, countConsecutive) = (1, 2) = 2
 3 4 9 10 20
• current element is 3
• prev + 1 == 3, therefore increment countConsecutive by 1
• countConsecutive = countConsecutive + 1 = 2 + 1 = 3
• update prev with current element, prev = 3
• pop the current element
• ans = max(ans, countConsecutive) = (2, 3) = 3
 4 9 10 20
• current element is 4
• prev + 1 == 4, therefore increment countConsecutive by 1
• countConsecutive = countConsecutive + 1 = 3 + 1 = 4
• update prev with current element, prev = 4
• pop the current element
• ans = max(ans, countConsecutive) = (3, 4) = 4
 9 10 20
• current element is 9
• prev + 1 != 9, therefore re-initialise countConsecutive by 1
• countConsecutive = 1
• update prev with current element, prev = 9
• pop the current element
• ans = max(ans, countConsecutive) = (4, 1) = 4
 10 20
• current element is 10
• prev + 1 == 10, therefore increment countConsecutive by 1
• countConsecutive = countConsecutive + 1 = 1 + 1 = 2
• update prev with current element, prev = 10
• pop the current element
• ans = max(ans, countConsecutive) = (4, 2) =4
 20
• current element is 20
• prev + 1 != 20, therefore re-initialise countConsecutive by 1
• countConsecutive = 1
• update prev with current element, prev = 20
• pop the current element
• ans = max(ans, countConsecutive) = (4, 1) = 4

Hence, the longest consecutive subsequence is 4.

Follow the steps below to solve the problem:

• Create a Priority Queue to store the element
• Store the first element in a variable
• Remove it from the Priority Queue
• Check the difference between this removed first element and the new peek element
• If the difference is equal to 1 increase the count by 1 and repeats step 2 and step 3
• If the difference is greater than 1 set counter to 1 and repeat step 2 and step 3
• if the difference is equal to 0 repeat step 2 and 3
• if counter greater than the previous maximum then store counter to maximum
• Continue step 4 to 7 until we reach the end of the Priority Queue
• Return the maximum value

Below is the implementation of the above approach:

## C++

 `// CPP program for the above approach` `#include ` `using` `namespace` `std;`   `int` `findLongestConseqSubseq(``int` `arr[], ``int` `N)` `{` `    ``priority_queue<``int``, vector<``int``>, greater<``int``> > pq;` `    ``for` `(``int` `i = 0; i < N; i++) {`   `        ``// adding element from` `        ``// array to PriorityQueue` `        ``pq.push(arr[i]);` `    ``}`   `    ``// Storing the first element` `    ``// of the Priority Queue` `    ``// This first element is also` `    ``// the smallest element` `    ``int` `prev = pq.top();` `    ``pq.pop();`   `    ``// Taking a counter variable with value 1` `    ``int` `c = 1;`   `    ``// Storing value of max as 1` `    ``// as there will always be` `    ``// one element` `    ``int` `max = 1;` `    ``while` `(!pq.empty()) {`   `        ``// check if current peek` `        ``// element minus previous` `        ``// element is greater than` `        ``// 1 This is done because` `        ``// if it's greater than 1` `        ``// then the sequence` `        ``// doesn't start or is broken here` `        ``if` `(pq.top() - prev > 1) {`   `            ``// Store the value of counter to 1` `            ``// As new sequence may begin` `            ``c = 1;`   `            ``// Update the previous position with the` `            ``// current peek And remove it` `            ``prev = pq.top();` `            ``pq.pop();` `        ``}`   `        ``// Check if the previous` `        ``//  element and peek are same` `        ``else` `if` `(pq.top() - prev == 0) {`   `            ``// Update the previous position with the` `            ``// current peek And remove it` `            ``prev = pq.top();` `            ``pq.pop();` `        ``}`   `        ``// If the difference` `        ``// between previous element and peek is 1` `        ``else` `{`   `            ``// Update the counter` `            ``// These are consecutive elements` `            ``c++;`   `            ``// Update the previous position` `            ``//  with the current peek And remove it` `            ``prev = pq.top();` `            ``pq.pop();` `        ``}`   `        ``// Check if current longest` `        ``// subsequence is the greatest` `        ``if` `(max < c) {`   `            ``// Store the current subsequence count as` `            ``// max` `            ``max = c;` `        ``}` `    ``}` `    ``return` `max;` `}`   `// Driver Code` `int` `main()` `{` `    ``int` `arr[] = { 1, 9, 3, 10, 4, 20, 2 };` `    ``int` `n = 7;`   `    ``cout << ``"Length of the Longest consecutive subsequence "` `            ``"is "` `         ``<< findLongestConseqSubseq(arr, n);` `    ``return` `0;` `}` `// this code is contributed by Manu Pathria`

## Java

 `// Java Program to find longest consecutive` `// subsequence This Program uses Priority Queue` `import` `java.io.*;` `import` `java.util.PriorityQueue;` `public` `class` `Longset_Sub {` `    ``// return the length of the longest` `    ``// subsequence of consecutive integers` `    ``static` `int` `findLongestConseqSubseq(``int` `arr[], ``int` `N)` `    ``{`   `        ``PriorityQueue pq` `            ``= ``new` `PriorityQueue();` `        ``for` `(``int` `i = ``0``; i < N; i++) {` `            ``// adding element from` `            ``// array to PriorityQueue` `            ``pq.add(arr[i]);` `        ``}`   `        ``// Storing the first element` `        ``// of the Priority Queue` `        ``// This first element is also` `        ``// the smallest element` `        ``int` `prev = pq.poll();`   `        ``// Taking a counter variable with value 1` `        ``int` `c = ``1``;`   `        ``// Storing value of max as 1` `        ``// as there will always be` `        ``// one element` `        ``int` `max = ``1``;`   `        ``for` `(``int` `i = ``1``; i < N; i++) {` `            ``// check if current peek` `            ``// element minus previous` `            ``// element is greater than` `            ``// 1 This is done because` `            ``// if it's greater than 1` `            ``// then the sequence` `            ``// doesn't start or is broken here` `            ``if` `(pq.peek() - prev > ``1``) {` `                ``// Store the value of counter to 1` `                ``// As new sequence may begin` `                ``c = ``1``;`   `                ``// Update the previous position with the` `                ``// current peek And remove it` `                ``prev = pq.poll();` `            ``}`   `            ``// Check if the previous` `            ``//  element and peek are same` `            ``else` `if` `(pq.peek() - prev == ``0``) {` `                ``// Update the previous position with the` `                ``// current peek And remove it` `                ``prev = pq.poll();` `            ``}` `            ``// if the difference` `            ``// between previous element and peek is 1` `            ``else` `{` `                ``// Update the counter` `                ``// These are consecutive elements` `                ``c++;`   `                ``// Update the previous position` `                ``//  with the current peek And remove it` `                ``prev = pq.poll();` `            ``}`   `            ``// Check if current longest` `            ``// subsequence is the greatest` `            ``if` `(max < c) {` `                ``// Store the current subsequence count as` `                ``// max` `                ``max = c;` `            ``}` `        ``}`   `        ``return` `max;` `    ``}`   `    ``// Driver Code` `    ``public` `static` `void` `main(String args[])` `        ``throws` `IOException` `    ``{` `        ``int` `arr[] = { ``1``, ``9``, ``3``, ``10``, ``4``, ``20``, ``2` `};` `        ``int` `n = arr.length;` `        ``System.out.println(` `            ``"Length of the Longest consecutive subsequence is "` `            ``+ findLongestConseqSubseq(arr, n));` `    ``}` `}` `// This code is contributed by Sudipa Sarkar`

## Python3

 `# Python program for the above approach` `import` `bisect`     `def` `findLongestConseqSubseq(arr, N):` `    ``pq ``=` `[]` `    ``for` `i ``in` `range``(N):`   `        ``# adding element from` `        ``# array to PriorityQueue` `        ``bisect.insort(pq, arr[i])`   `    ``# Storing the first element` `    ``# of the Priority Queue` `    ``# This first element is also` `    ``# the smallest element` `    ``prev ``=` `pq[``0``]` `    ``pq.pop(``0``)`   `    ``# Taking a counter variable with value 1` `    ``c ``=` `1`   `    ``# Storing value of max as 1` `    ``# as there will always be` `    ``# one element` `    ``max` `=` `1` `    ``while``(``len``(pq)):` `        ``# check if current peek` `        ``# element minus previous` `        ``# element is greater than` `        ``# 1 This is done because` `        ``# if it's greater than 1` `        ``# then the sequence` `        ``# doesn't start or is broken here` `        ``if``(pq[``0``] ``-` `prev > ``1``):` `            ``# Store the value of counter to 1` `            ``# As new sequence may begin` `            ``c ``=` `1`   `            ``# Update the previous position with the` `            ``# current peek And remove it` `            ``prev ``=` `pq[``0``]` `            ``pq.pop(``0``)`   `        ``# Check if the previous` `        ``# element and peek are same` `        ``elif``(pq[``0``] ``-` `prev ``=``=` `0``):` `            ``# Update the previous position with the` `            ``# current peek And remove it` `            ``prev ``=` `pq[``0``]` `            ``pq.pop(``0``)`   `        ``# If the difference` `        ``# between previous element and peek is 1` `        ``else``:` `            ``# Update the counter` `            ``# These are consecutive elements` `            ``c ``=` `c ``+` `1` `            ``# Update the previous position` `            ``# with the current peek And remove it` `            ``prev ``=` `pq[``0``]` `            ``pq.pop(``0``)`   `        ``# Check if current longest` `        ``# subsequence is the greatest` `        ``if``(``max` `< c):` `            ``# Store the current subsequence count as` `            ``# max` `            ``max` `=` `c` `    ``return` `max`     `# Driver Code` `arr ``=` `[``1``, ``9``, ``3``, ``10``, ``4``, ``20``, ``2``]` `n ``=` `7` `print``(``"Length of the Longest consecutive subsequence is {}"``.``format``(` `    ``findLongestConseqSubseq(arr, n)))`     `# This code is contributed by Pushpesh Raj`

## C#

 `// C# program to implement` `// the above approach` `using` `System;` `using` `System.Collections.Generic;`   `class` `GFG {`   `    ``// return the length of the longest` `    ``// subsequence of consecutive integers` `    ``static` `int` `findLongestConseqSubseq(``int``[] arr, ``int` `N)` `    ``{`   `        ``List<``int``> pq = ``new` `List<``int``>();` `        ``for` `(``int` `i = 0; i < N; i++) {`   `            ``// adding element from` `            ``// array to PriorityQueue` `            ``pq.Add(arr[i]);` `            ``pq.Sort();` `        ``}`   `        ``// Storing the first element` `        ``// of the Priority Queue` `        ``// This first element is also` `        ``// the smallest element` `        ``int` `prev = pq;`   `        ``// Taking a counter variable with value 1` `        ``int` `c = 1;`   `        ``// Storing value of max as 1` `        ``// as there will always be` `        ``// one element` `        ``int` `max = 1;`   `        ``for` `(``int` `i = 1; i < N; i++) {`   `            ``// check if current peek` `            ``// element minus previous` `            ``// element is greater than` `            ``// 1 This is done because` `            ``// if it's greater than 1` `            ``// then the sequence` `            ``// doesn't start or is broken here` `            ``if` `(pq - prev > 1) {` `                ``// Store the value of counter to 1` `                ``// As new sequence may begin` `                ``c = 1;`   `                ``// Update the previous position with the` `                ``// current peek And remove it` `                ``prev = pq;` `                ``pq.RemoveAt(0);` `            ``}`   `            ``// Check if the previous` `            ``//  element and peek are same` `            ``else` `if` `(pq - prev == 0) {`   `                ``// Update the previous position with the` `                ``// current peek And remove it` `                ``prev = pq;` `                ``pq.RemoveAt(0);` `            ``}`   `            ``// if the difference` `            ``// between previous element and peek is 1` `            ``else` `{`   `                ``// Update the counter` `                ``// These are consecutive elements` `                ``c++;`   `                ``// Update the previous position` `                ``//  with the current peek And remove it` `                ``prev = pq;` `                ``pq.RemoveAt(0);` `            ``}`   `            ``// Check if current longest` `            ``// subsequence is the greatest` `            ``if` `(max < c) {`   `                ``// Store the current subsequence count as` `                ``// max` `                ``max = c;` `            ``}` `        ``}`   `        ``return` `max;` `    ``}`   `    ``// Driver Code` `    ``public` `static` `void` `Main()` `    ``{` `        ``int``[] arr = { 1, 9, 3, 10, 4, 20, 2 };` `        ``int` `n = arr.Length;` `        ``Console.WriteLine(` `            ``"Length of the Longest consecutive subsequence is "` `            ``+ findLongestConseqSubseq(arr, n));` `    ``}` `}`   `// This code is contributed by code_hunt.`

## Javascript

 `function` `findLongestConseqSubseq(arr, N) {` `  ``let pq = ``new` `PriorityQueue();`   `  ``for` `(let i = 0; i < N; i++) {` `    ``pq.push(arr[i]);` `  ``}`   `  ``let prev = pq.poll();` `  ``let c = 1;` `  ``let max = 1;`   `  ``for` `(let i = 1; i < N; i++) {` `    ``if` `(pq.peek() - prev > 1) {` `      ``c = 1;` `      ``prev = pq.poll();` `    ``} ``else` `if` `(pq.peek() - prev == 0) {` `      ``prev = pq.poll();` `    ``} ``else` `{` `      ``c++;` `      ``prev = pq.poll();` `    ``}`   `    ``if` `(max < c) {` `      ``max = c;` `    ``}` `  ``}`   `  ``return` `max;` `}`   `class PriorityQueue {` `  ``constructor() {` `    ``this``.items = [];` `  ``}`   `  ``push(element) {` `    ``this``.items.push(element);` `    ``this``.bubbleUp(``this``.items.length - 1);` `  ``}`   `  ``peek() {` `    ``if` `(``this``.items.length === 0) {` `      ``return` `null``;` `    ``}`   `    ``return` `this``.items;` `  ``}`   `  ``poll() {` `    ``if` `(``this``.items.length === 0) {` `      ``return` `null``;` `    ``}`   `    ``const root = ``this``.items;` `    ``const last = ``this``.items.pop();`   `    ``if` `(``this``.items.length > 0) {` `      ``this``.items = last;` `      ``this``.bubbleDown(0);` `    ``}`   `    ``return` `root;` `  ``}`   `  ``bubbleUp(index) {` `    ``while` `(index > 0) {` `      ``const parentIndex = Math.floor((index - 1) / 2);`   `      ``if` `(``this``.items[parentIndex] <= ``this``.items[index]) {` `        ``break``;` `      ``}`   `      ``const temp = ``this``.items[parentIndex];` `      ``this``.items[parentIndex] = ``this``.items[index];` `      ``this``.items[index] = temp;`   `      ``index = parentIndex;` `    ``}` `  ``}`   `  ``bubbleDown(index) {` `    ``while` `(``true``) {` `      ``const leftChildIndex = 2 * index + 1;` `      ``const rightChildIndex = 2 * index + 2;` `      ``let smallestChildIndex = index;`   `      ``if` `(` `        ``leftChildIndex < ``this``.items.length &&` `        ``this``.items[leftChildIndex] < ``this``.items[smallestChildIndex]` `      ``) {` `        ``smallestChildIndex = leftChildIndex;` `      ``}`   `      ``if` `(` `        ``rightChildIndex < ``this``.items.length &&` `        ``this``.items[rightChildIndex] < ``this``.items[smallestChildIndex]` `      ``) {` `        ``smallestChildIndex = rightChildIndex;` `      ``}`   `      ``if` `(smallestChildIndex === index) {` `        ``break``;` `      ``}`   `      ``const temp = ``this``.items[smallestChildIndex];` `      ``this``.items[smallestChildIndex] = ``this``.items[index];` `      ``this``.items[index] = temp;`   `      ``index = smallestChildIndex;` `    ``}` `  ``}` `}`   `const arr = [1, 9, 3, 10, 4, 20, 2];` `const n = arr.length;` `console.log(` `  ``"Length of the Longest consecutive subsequence is "` `+` `    ``findLongestConseqSubseq(arr, n)` `);`

Output

```Length of the Longest consecutive subsequence is 4

```

Time Complexity: O(N*log(N)), Time required to push and pop N elements is logN for each element.
Auxiliary Space: O(N), Space required by priority queue to store N elements.

### Longest Consecutive Subsequence using Dynamic Programming:

For each number in the input array find the longest possible consecutive sequence starting at that number

For e.g. if input is [3, 2, 1], find the longest possible sequence starting with 3, 2, 1. Each time you find the longest possible sequence
memoize the sequence length for future use.

For e.g. once you find the longest possible sequence starting with 3, of length 1 (since there is no other number after 3) and you need to find the longest sequence starting at 2, you do not need to recalculate the length of sequence starting with 3 as you have solved this sub-problem before. So you can reuse the memoized value.

To solve this problem, we store the current consecutive count in dp[i].

When we have a sorted array: [1, 3, 4, 4, 5], the output is 3. So we want dp[i] to remains unchanged when sorted[i] equals to sorted[i-1], in this case dp is [1, 1, 2, 2, 3].

And we reset dp[i] to 1 if sorted[i] – sorted[i-1] is not equals to 0 or 1.

Sort the array to make sure the number is in ascending order.
Initialize the parameters
max = 0
dp = 1
Loop through the sorted array
If sorted[i] – sorted[i-1] equals to 1 => dp[i] = dp[i-1] + 1 and update max if dp[i] > original max
else if sorted[i] – sorted[i-1] equals to 0 => dp[i] = 1
else dp[i] = 1
Return the maximum.

## C++

 `#include ` `#include ` `#include `   `using` `namespace` `std;`   `int` `dfs(``int` `start, unordered_map<``int``, ``int``>& longest);`   `int` `longestConsecutive(vector<``int``>& nums) {` `    ``// Base case` `    ``if` `(nums.size() <= 1) {` `        ``return` `nums.size();` `    ``}`   `    ``int` `max = 1;` `    ``unordered_map<``int``, ``int``> longest;`   `    ``// Add all elements to the hashmap` `    ``for` `(``int` `n : nums) {` `        ``longest[n] = 0;` `    ``}`   `    ``// Iterate through the numbers and find the longest consecutive subsequence` `    ``for` `(``int` `i = 0; i < nums.size(); i++) {` `        ``max = std::max(max, dfs(nums[i], longest));` `    ``}`   `    ``return` `max;` `}`   `int` `dfs(``int` `start, unordered_map<``int``, ``int``>& longest) {` `    ``if` `(longest.find(start) == longest.end()) {` `        ``return` `0;` `    ``}`   `    ``if` `(longest[start] != 0) {` `        ``return` `longest[start];` `    ``}`   `    ``int` `currentLongest = 1 + dfs(start + 1, longest);` `    ``longest[start] = currentLongest;` `    ``return` `currentLongest;` `}`   `int` `main() {` `    ``vector<``int``> arr = {1, 9, 3, 10, 4, 20, 2};` `    ``cout << ``"Length of the Longest consecutive subsequence is "` `         ``<< longestConsecutive(arr) << endl;` `    ``return` `0;` `}`

## Java

 `// Java Program to find longest consecutive` `// subsequence This Program uses dynamic programming and hashmap` `import` `java.io.*;` `import` `java.util.*;` `public` `class` `Longset_Sub {` `       ``public` `static` `int` `longestConsecutive(``int``[] nums) {` `        ``//base case` `        ``if` `(nums.length <= ``1``) {` `            ``return` `nums.length;` `        ``}` `        ``//declare a max varaibale` `        ``int` `max = ``1``;` `        ``Map longest = ``new` `HashMap();` `        ``for` `(``int` `n : nums) {` `            ``longest.put(n, ``null``);` `        ``}` `        ``//Run a loop to store the maximum value in the max varibale` `        ``for` `(``int` `i = ``0``; i < nums.length; i++) {` `            ``max = Math.max(max, dfs(nums[i], longest));` `        ``}` `        `  `        ``return` `max;` `    ``}` `    ``//Run a dfs across every consecutive values` `    ``private` `static` `int` `dfs(``int` `start, Map longest) {` `        ``if` `(!longest.containsKey(start)) {` `            ``return` `0``;` `        ``}` `        ``//check if the values are present in the map before hand` `        ``if` `(longest.get(start) != ``null``) {` `            ``return` `longest.get(start);` `        ``}` `        ``//store the values in the currentlongest variable` `        ``int` `currentLongest = ``1` `+ dfs(start + ``1``, longest);` `        `  `        ``longest.put(start, currentLongest);` `        `  `        ``return` `currentLongest;` `    ``}`   `    ``// Driver Code` `    ``public` `static` `void` `main(String args[])` `        ``throws` `IOException` `    ``{` `      ``//declare a array` `        ``int` `arr[] = { ``1``, ``9``, ``3``, ``10``, ``4``, ``20``, ``2` `};` `        ``int` `n = arr.length;` `        ``System.out.println(` `            ``"Length of the Longest consecutive subsequence is "` `            ``+ longestConsecutive(arr));` `    ``}` `}` `// This code is contributed by Sudipa Sarkar`

## Python3

 `def` `dfs(start, longest):` `    ``if` `start ``not` `in` `longest:` `        ``return` `0` `    `  `    ``if` `longest[start] !``=` `0``:` `        ``return` `longest[start]` `    `  `    ``current_longest ``=` `1` `+` `dfs(start ``+` `1``, longest)` `    ``longest[start] ``=` `current_longest` `    ``return` `current_longest`   `def` `longest_consecutive(nums):` `    ``# Base case` `    ``if` `len``(nums) <``=` `1``:` `        ``return` `len``(nums)` `    `  `    ``max_length ``=` `1` `    ``longest ``=` `{}`   `    ``# Add all elements to the hashmap` `    ``for` `n ``in` `nums:` `        ``longest[n] ``=` `0`   `    ``# Iterate through the numbers and find the longest consecutive subsequence` `    ``for` `num ``in` `nums:` `        ``max_length ``=` `max``(max_length, dfs(num, longest))`   `    ``return` `max_length`   `# Test` `arr ``=` `[``1``, ``9``, ``3``, ``10``, ``4``, ``20``, ``2``]` `print``(``"Length of the Longest consecutive subsequence is"``, longest_consecutive(arr))`

## C#

 `using` `System;` `using` `System.Collections.Generic;`   `class` `LongestConsecutiveSequence` `{` `    ``static` `int` `Dfs(``int` `start, Dictionary<``int``, ``int``> longest)` `    ``{` `        ``if` `(!longest.ContainsKey(start))` `        ``{` `            ``return` `0;` `        ``}`   `        ``if` `(longest[start] != 0)` `        ``{` `            ``return` `longest[start];` `        ``}`   `        ``int` `currentLongest = 1 + Dfs(start + 1, longest);` `        ``longest[start] = currentLongest;` `        ``return` `currentLongest;` `    ``}`   `    ``static` `int` `LongestConsecutive(``int``[] nums)` `    ``{` `        ``// Base case` `        ``if` `(nums.Length <= 1)` `        ``{` `            ``return` `nums.Length;` `        ``}`   `        ``int` `max = 1;` `        ``Dictionary<``int``, ``int``> longest = ``new` `Dictionary<``int``, ``int``>();`   `        ``// Add all elements to the dictionary` `        ``foreach` `(``int` `n ``in` `nums)` `        ``{` `            ``longest[n] = 0;` `        ``}`   `        ``// Iterate through the numbers and find the longest consecutive subsequence` `        ``for` `(``int` `i = 0; i < nums.Length; i++)` `        ``{` `            ``max = Math.Max(max, Dfs(nums[i], longest));` `        ``}`   `        ``return` `max;` `    ``}`   `    ``static` `void` `Main(``string``[] args)` `    ``{` `        ``int``[] arr = { 1, 9, 3, 10, 4, 20, 2 };` `        ``Console.WriteLine(``"Length of the Longest consecutive subsequence is "` `+ LongestConsecutive(arr));` `    ``}` `}`

## Javascript

 `function` `longestConsecutive(nums) {` `    ``// Base case: If there are 0 or 1 element, return the size of nums` `    ``if` `(nums.length <= 1) {` `        ``return` `nums.length;` `    ``}`   `    ``let max = 1;` `    ``const longest = ``new` `Map();`   `    ``// Add all elements to the Map` `    ``for` `(const n of nums) {` `        ``longest.set(n, ``null``);` `    ``}`   `    ``// Iterate through the numbers and find the longest consecutive subsequence` `    ``for` `(let i = 0; i < nums.length; i++) {` `        ``max = Math.max(max, dfs(nums[i], longest));` `    ``}`   `    ``return` `max;` `}`   `// Run a depth-first search (dfs) across consecutive values` `function` `dfs(start, longest) {` `    ``if` `(!longest.has(start)) {` `        ``return` `0;` `    ``}`   `    ``// Check if the value is present in the Map` `    ``if` `(longest.get(start) !== ``null``) {` `        ``return` `longest.get(start);` `    ``}`   `    ``// Store the value in the currentLongest variable` `    ``const currentLongest = 1 + dfs(start + 1, longest);`   `    ``longest.set(start, currentLongest);`   `    ``return` `currentLongest;` `}`   `// Driver Code` `const arr = [1, 9, 3, 10, 4, 20, 2];` `console.log(``"Length of the Longest consecutive subsequence is "` `+ longestConsecutive(arr));`

Output

```Length of the Longest consecutive subsequence is 4

```

Time complexity: O(N), Only one traversal is needed and the time complexity is O(n) under the assumption that hash insert and search takes O(1) time.
Auxiliary space: O(N), To store every element in the hashmap O(n) space is needed.

Feeling lost in the world of random DSA topics, wasting time without progress? It's time for a change! Join our DSA course, where we'll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 geeks!

Previous
Next