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

Updated on: 19-Jan-2021

401 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements