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 

4
2

How It Works

The function works by comparing each element with the previous one:

  1. Start with count = 1 and max = 1 (minimum sequence length)
  2. For each element, check if it equals the previous element plus 1
  3. If yes, increment count and update max if needed
  4. If no, reset count to 1 (start new sequence)
  5. 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.

Updated on: 2026-03-15T23:18:59+05:30

390 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements