Can array form consecutive sequence - JavaScript

We are required to write a JavaScript function that takes in an array of numbers and checks if the elements of the array can be rearranged to form a sequence of consecutive numbers or not.

For example, if we have an array [3, 1, 4, 2, 5], these numbers can be rearranged as [1, 2, 3, 4, 5] to form a consecutive sequence.

Problem Understanding

A consecutive sequence means each number is exactly 1 more than the previous number. To check this, we need to:

  • Sort the array in ascending order
  • Verify each element is exactly 1 more than the previous element
  • Handle edge cases like empty arrays or single elements

Example Input and Expected Output

If the array is:

const arr = [3, 1, 4, 2, 5];

Then the output should be:

true

Implementation

Here's the complete solution:

const arr = [3, 1, 4, 2, 5];

const canBeConsecutive = (arr = []) => {
    if (!arr.length) {
        return false;
    }
    
    const copy = arr.slice();
    copy.sort((a, b) => a - b);
    
    for (let i = copy[0], j = 0; j < copy.length; i++, j++) {
        if (copy[j] === i) {
            continue;
        }
        return false;
    }
    return true;
};

console.log(canBeConsecutive(arr));
true

How It Works

The function follows these steps:

  1. Edge Case: Returns false for empty arrays
  2. Create Copy: Uses slice() to avoid modifying the original array
  3. Sort: Arranges numbers in ascending order
  4. Check Sequence: Starting from the first element, verifies each subsequent element is exactly 1 more

Testing with Different Cases

const canBeConsecutive = (arr = []) => {
    if (!arr.length) {
        return false;
    }
    
    const copy = arr.slice();
    copy.sort((a, b) => a - b);
    
    for (let i = copy[0], j = 0; j < copy.length; i++, j++) {
        if (copy[j] === i) {
            continue;
        }
        return false;
    }
    return true;
};

// Test cases
console.log(canBeConsecutive([3, 1, 4, 2, 5]));    // true
console.log(canBeConsecutive([1, 3, 5]));          // false
console.log(canBeConsecutive([7]));                // true
console.log(canBeConsecutive([]));                 // false
console.log(canBeConsecutive([10, 12, 11]));       // true
true
false
true
false
true

Key Points

  • Single-element arrays return true (trivially consecutive)
  • Empty arrays return false by design choice
  • The algorithm has O(n log n) time complexity due to sorting
  • Space complexity is O(n) for creating the copy

Conclusion

This solution efficiently checks if an array can form a consecutive sequence by sorting first, then verifying each element follows the consecutive pattern. The approach handles various edge cases and works for arrays of any size.

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

281 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements