
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Length of the Longest Possible Consecutive Sequence of Numbers in JavaScript
We are required to write a JavaScript function that takes in an array of integers as the first and the only argument.
The function should find and return the length of the longest consecutive increasing sequence that exists in the array (contiguous or non-contiguous).
For example −
If the input array is −
const arr = [4, 6, 9, 1, 2, 8, 5, 3, -1];
Then the output should be 6 because the longest consecutive increasing sequence is 1, 2, 3, 4, 5, 6.
Example
Following is the code −
const arr = [4, 6, 9, 1, 2, 8, 5, 3, -1]; const consecutiveSequence = (arr = []) => { const consecutiveRight = {}; let max = 0; for (let i = 0; i < arr.length; i += 1) { let curr = arr[i]; if (consecutiveRight[curr] !== undefined) { continue; // We already have this number. consecutiveRight[curr] = 1 + (consecutiveRight[curr + 1] || 0); while (consecutiveRight[curr - 1] !== undefined) { consecutiveRight[curr - 1] = consecutiveRight[curr] + 1; curr -= 1; } max = Math.max(max, consecutiveRight[curr]); } return max; }; console.log(consecutiveSequence(arr));
Output
Following is the console output −
6
Advertisements