5 Best Ways to Check if Array Elements are Consecutive in Python

Rate this post

πŸ’‘ Problem Formulation: In various programming scenarios, you might be tasked with verifying whether elements within an array follow a sequential order without any gaps. For instance, given the input array [2, 3, 4, 5, 6], the desired output should affirm that the array contains consecutive elements. Conversely, the array [4, 5, 7, 8] should yield a negative result due to the absence of the number 6.

Method 1: Iterative Comparison

This method consists of iterating through the array and checking if each element is one number higher than the previous one. It is a straightforward and intuitive approach that works well with sorted arrays.

Here’s an example:

def are_consecutive(arr):
    return all(arr[i] == arr[i-1] + 1 for i in range(1, len(arr)))

# Example usage:
print(are_consecutive([5, 6, 7, 8, 9]))

Output: True

This code snippet defines a function are_consecutive that takes an array arr as its parameter. It uses Python’s built-in all() function to check the consecutive property by verifying the condition that each element except the first should be one greater than its predecessor. It returns a Boolean value indicating whether the array elements are consecutive.

Method 2: Using the Range Function

If the array is expected to start and end at specific values, we can utilize Python’s range() function to generate a list of consecutive numbers and compare it to the input array after sorting.

Here’s an example:

def are_consecutive(arr):
    return arr == list(range(min(arr), max(arr)+1))

# Example usage:
print(are_consecutive([5, 3, 4, 6, 7]))

Output: True

The are_consecutive function compares the sorted input array to a list of consecutive integers generated from the minimum to the maximum value found in the array. This method is robust and works regardless of whether the input array is initially sorted or not.

Method 3: Using Set and Range

This method leverages the uniqueness property of Python sets to discard duplicate values and validate consecutive elements by comparing the set size with the range of elements.

Here’s an example:

def are_consecutive(arr):
    unique_nums = set(arr)
    return len(unique_nums) == max(unique_nums) - min(unique_nums) + 1

# Example usage:
print(are_consecutive([3, 4, 5, 6, 7]))

Output: True

This function, are_consecutive, converts the array to a set to remove any duplicates and then compares the length of this set to the range between the smallest and largest numbers. This method efficiently takes care of duplicates and unsorted arrays.

Method 4: Checking Consecutive Elements After Sorting

This technique involves sorting the array first and then checking if each pair of adjacent elements differ by exactly one, ensuring that the entire array is consecutive.

Here’s an example:

def are_consecutive(arr):
    sorted_arr = sorted(arr)
    return all(sorted_arr[i] == sorted_arr[i-1] + 1 for i in range(1, len(sorted_arr)))

# Example usage:
print(are_consecutive([10, 11, 9, 8, 7]))

Output: False

The function are_consecutive first sorts the input array and then, similarly to Method 1, uses the all() function to check for consecutive elements. The strength of this method is that it can work with unsorted arrays while still efficiently determining consecutiveness.

Bonus One-Liner Method 5: Using Min-Max and Length

This compact method calculates if the array elements are consecutive by checking if the difference between the maximum and minimum values plus one equals the length of the array.

Here’s an example:

are_consecutive = lambda arr: max(arr) - min(arr) + 1 == len(arr)

# Example usage:
print(are_consecutive([14, 13, 12, 11]))

Output: True

The one-liner are_consecutive employs a lambda function to perform the conditional check succinctly. It’s an elegant solution that assumes the array contains no duplicates and is beneficial for arrays where the start and end elements should encompass the entire range.

Summary/Discussion

  • Method 1: Iterative Comparison. Straightforward and intuitive. Requires sorted input.
  • Method 2: Range Function. Robust and independent of input array order. Slightly less efficient due to sort and range generation.
  • Method 3: Set and Range. Handles duplicates with ease. Efficiency can degrade for large arrays with wide ranges but few elements.
  • Method 4: Consecutive Elements After Sorting. Works with unsorted arrays. Sorting adds computational cost.
  • Bonus Method 5: Min-Max and Length One-Liner. Elegant and efficient for specific scenarios. Does not account for duplicates.