How to useSorting in JavaScript in Javascript
- In this apporach, we are using the Sorting apporach, were firstly we are checking whteger the array is empty, of not, then we are sorting the array in the asecending order.
- After that, we are going thorugh all thw alements of the array by maintinag the count of the consequtib element.
- The longest subsequence is the maxium count whilch will be printed at the end.
Example: In this example, we will find the longest consecutive sequence of numbers in an array using Sorting technique in JavaScript.
Javascript
function longConsequtiveSeqUsingSorting(inputarray) { if (inputarray.length === 0) { return 0; } inputarray.sort((a, b) => a - b); let countValue = 1; let maxcountValue = 1; for (let i = 1; i < inputarray.length; i++) { if (inputarray[i - 1] + 1 === inputarray[i]) { countValue++; } else if (inputarray[i - 1] !== inputarray[i]) { countValue = 1; } maxcountValue = Math.max(maxcountValue, countValue); } return maxcountValue; } const inputArray = [1, 9, 3, 10, 4, 20, 2]; const outputLongValue = longConsequtiveSeqUsingSorting(inputArray); console.log(outputLongValue); |
4
Time Complexity: O(N * log(N))
Space Complexity: O(1)
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