How to useJavaScript Set in Javascript
- In this approach, we use the JS Set that finds the longest consecutive subsequence. We take the array as the input and check if the array is empty, if it is not empty then we create the set of all elements in the input array.
- Then we iterate through the input array. For each element, we are checking the predecessor is in the set, if it is not, then we are starting a new consecutive subsequence with that element.
- We are keeping track of the length of the longest consecutive subsequence and printing it at the end.
Example: In this example, we will find the longest consecutive sequence of numbers in an array using Set in JavaScript.
Javascript
function longConsequtiveSeqUsingSet(inputarry) { if (inputarry == null || inputarry.length === 0) { return 0; } let set = new Set(inputarry); let outputLongValue = 0; for (let temp of inputarry) { if (!set.has(temp - 1)) { let count = 0; while (set.has(count + temp)) { count++; } outputLongValue = Math.max( outputLongValue, count ); } } return outputLongValue; } let inputArray = [36, 41, 56, 35, 44, 33, 34, 92, 43, 32, 42]; console.log(longConsequtiveSeqUsingSet(inputArray)); |
5
Time compexity: O(n)
Space compleity: O(n)
JavaScript Program to find the Longest Consecutive Sequence of Numbers in an Array
In this article, we are going to find the longest consecutive sequence of numbers in an array using JavaScript language. We are given an array that consists of integers we need to find the longest subsequence such that elements in the subsequence are consecutive integers, these numbers are in any order.
Example:
Input: inputArray[] = [1, 9, 3, 10, 4, 20, 2]
Output: 4
Explanation: The subsequence 1, 3, 4, 2 is the longest subsequence of consecutive elements