Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Find the longest sub array of consecutive numbers with a while loop in JavaScript
We are required to write a function with a while-statement that determines the length of the largest consecutive subarray in an array of positive integers.
For instance, if we have an array like [6, 7, 8, 6, 12, 1, 2, 3, 4], the longest consecutive sequence is [1, 2, 3, 4] with length 4.
Problem Understanding
Let's look at some examples to understand the problem better:
Input: [6, 7, 8, 6, 12, 1, 2, 3, 4] Consecutive sequence: [1, 2, 3, 4] Output: 4
Input: [5, 6, 1, 8, 9, 7] Consecutive sequence: [8, 9] Output: 2
Algorithm Approach
We'll use a while loop to iterate through the array and track consecutive numbers. The algorithm maintains three variables:
- count: Current consecutive sequence length
- max: Maximum consecutive sequence length found so far
- len: Current index in the array
Implementation
const arr = [6, 7, 8, 6, 12, 1, 2, 3, 4];
const arr1 = [5, 6, 1, 8, 9, 7];
const findLongestSub = arr => {
let count = 1, len = 0, max = 1;
while(len < arr.length){
if(arr[len] === arr[len - 1] + 1){
count++;
if(max < count){
max = count;
}
} else {
count = 1;
}
len++;
}
return max;
};
console.log(findLongestSub(arr)); // First example
console.log(findLongestSub(arr1)); // Second example
4 2
How It Works
The function works by comparing each element with the previous one:
- Start with
count = 1andmax = 1(minimum sequence length) - For each element, check if it equals the previous element plus 1
- If yes, increment
countand updatemaxif needed - If no, reset
countto 1 (start new sequence) - Continue until all elements are processed
Edge Cases
The function handles common edge cases:
// Single element array console.log(findLongestSub([5])); // 1 // No consecutive numbers console.log(findLongestSub([1, 3, 5, 7])); // 1 // All consecutive numbers console.log(findLongestSub([1, 2, 3, 4, 5])); // 5
1 1 5
Conclusion
This while-loop solution efficiently finds the longest consecutive subarray in O(n) time complexity. The algorithm tracks consecutive sequences and returns the maximum length found.
