- Trending Categories
- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- 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

- Related Questions & Answers
- Program to find length of longest consecutive sequence in Python
- Find the Length of the Longest possible palindrome string JavaScript
- Longest Consecutive Sequence in Python
- Binary Tree Longest Consecutive Sequence in C++
- Find the longest sub array of consecutive numbers with a while loop in JavaScript
- Binary Tree Longest Consecutive Sequence II in C++
- Program to find length of longest possible stick in Python?
- Length of longest string chain in JavaScript
- Sum of consecutive numbers in JavaScript
- Longest string consisting of n consecutive strings in JavaScript
- Find length of the longest consecutive path from a given starting characters in C++
- Program to find length of longest consecutive path of a binary tree in python
- Find and return the longest length of set in JavaScript
- Program to find length of longest consecutive sublist with unique elements in Python
- Finding longest consecutive joins in JavaScript

Advertisements