- 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?
- Sum of consecutive numbers in JavaScript
- Length of longest string chain 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
- Longest string consisting of n consecutive strings in JavaScript
- Find and return the longest length of set in JavaScript
- Finding the character with longest consecutive repetitions in a string and its length using JavaScript
- Print all possible sums of consecutive numbers with sum N in C++

- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who

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.

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));

Following is the console output −

6

Advertisements