Check if items in an array are consecutive but WITHOUT SORTING in JavaScript

In JavaScript, checking if array items are consecutive without sorting requires verifying that elements form an unbroken sequence. We can solve this using mathematical properties and built-in array methods.

What are Consecutive Items in an Array?

Consecutive elements form an unbroken sequence where each number differs by exactly 1 from the next. For example, [1, 2, 3, 4, 5] contains consecutive items in ascending order, while [5, 4, 3, 2, 1] is consecutive in descending order.

Example Input/Output

Input:

[11, 12, 13]

Output:

true

Input:

[21, 11, 10]

Output:

false

Method 1: Using Min/Max Range Check

This approach finds the minimum and maximum values, then verifies that all numbers in the expected range exist in the array.

function isConsecutive(arr) {
    if (arr.length 

true
true
false

Method 2: Sum Comparison Approach

This method compares the expected sum of consecutive numbers with the actual array sum. For consecutive numbers, the sum equals: (count × (first + last)) / 2

function isConsecutive(arr) {
    if (arr.length  sum + num, 0);
    
    return expectedSum === actualSum;
}

const arr1 = [13, 12, 11, 10];
const arr2 = [8, 4, 5, 6, 7, 10];
const arr3 = [1, 2, 3, 4, 5];

console.log(isConsecutive(arr1)); // true
console.log(isConsecutive(arr2)); // false
console.log(isConsecutive(arr3)); // true
true
false
true

Method Comparison

Method Time Complexity Space Complexity Approach
Range Check O(n²) O(1) Uses indexOf() in loop
Sum Comparison O(n) O(1) Mathematical calculation

Key Points

  • Both methods handle arrays in any order without sorting
  • Range check: max - min must equal length - 1
  • Sum method is more efficient with O(n) complexity
  • Arrays with single elements return false by convention

Conclusion

The sum comparison method offers better performance for checking consecutive elements without sorting. Both approaches verify that elements form an unbroken numerical sequence regardless of their arrangement in the array.

Updated on: 2026-03-15T23:19:00+05:30

967 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements