Check If Array Elements Are Consecutive in Python



Suppose we have an array of numbers called nums. We have to check whether it contains contiguous values or not. So, if the input is like nums = [6, 8, 3, 5, 4, 7], then the output will be true as the elements are 3, 4, 5, 6, 7, 8. Following is the sample example to check if elements of an array are consecutive.

def solve(nums):
   if len(nums) < 1:
      return False
   min_val = min(nums)
   max_val = max(nums)
   if max_val - min_val + 1 == len(nums):
      for i in range(len(nums)):
         if nums[i] < 0:
            j = -nums[i] - min_val
         else:
            j = nums[i] - min_val
            if nums[j] > 0:
               nums[j] = -nums[j]
            else:
               return False
      return True
   return False
nums = [6, 8, 3, 5, 4, 7]
print(solve(nums))

Following is the output of the above code ?

True

In Python, to check if an array of numbers contains consecutive values, we can use various methods. Here's an overview of four different methods.

Using 'sort()'

In this method, we sort the array and then check if the difference between the maximum and minimum values is equal to the length of the array minus one. If this condition holds, the numbers must be consecutive.

Example

In the following example, the array was sorted by using the sort() function. once sorted, you can check each adjacent pair of numbers to see if they differ by 1. If all adjacent pairs meet this condition, the numbers are consecutive.

def are_consecutive_sorting(nums):
    if len(nums) < 1:
        return False
    nums.sort()
    for i in range(len(nums) - 1):
        if nums[i] + 1 != nums[i + 1]:
            return False
    return True
nums = [6, 8, 3, 5, 4, 7]
print(are_consecutive_sorting(nums))

Output

Following is the output of the above code ?

True

Using Visited Array

This method creates a boolean array to track each number within a specific range. We then mark each number that appears and finally check if all required indices in the boolean array are 'True'.

Example

In this example, we create a boolean array to track which numbers within the range (from min to max of the input) appear in the input. If all positions in this array are marked True, the numbers are consecutive.

def are_consecutive_visited_array(nums):
    if len(nums) < 1:
        return False
    
    min_val = min(nums)
    max_val = max(nums)
    if max_val - min_val + 1 != len(nums):
        return False
    
    visited = [False] * (max_val - min_val + 1)
    
    for num in nums:
        visited[num - min_val] = True
    
    return all(visited)

nums = [6, 8, 3, 5, 4, 7]
print(are_consecutive_visited_array(nums))

Output

True

Marking Visited Array Elements as Negative

This method modifies the original array to keep track of which numbers have been encountered by marking their corresponding indices as negative. If an index is accessed twice, it indicates that the sequence is not consecutive.

Example

In the following example, the seen numbers by marking their corresponding indices as negative. If it finds a duplicate (an index already negative), it concludes the numbers are not consecutive.

def are_consecutive_marking_negative(nums):
    if len(nums) < 1:
        return False
    
    min_val = min(nums)
    
    for num in nums:
        index = abs(num) - min_val
        
        if nums[index] < 0:
            return False  # Found a duplicate
        nums[index] = -nums[index]  # Mark the number as seen by making it negative
        
    return True
nums = [6, 8, 3, 5, 4, 7]
print(are_consecutive_marking_negative(nums))

Output

True

Using XOR Property

The XOR method is based on the properties of the XOR operation, where 'x ^ x = 0' and 'x ^ 0 = x'. In this approach, we first XOR all the numbers in the array and then XOR all the natural numbers in the range defined by the minimum and maximum values in that array. If the final results of both XOR operations match, it indicates that the numbers in the array are consecutive.

Example

The following code computes the XOR of all numbers in the array and the XOR of all numbers in the complete range. If both results match, it confirms that the array contains all consecutive integers.

def are_consecutive_xor(nums):
    if len(nums) < 1:
        return False
    min_val = min(nums)
    max_val = max(nums)
    
    if max_val - min_val + 1 != len(nums):
        return False
    xor_array = 0
    xor_range = 0
    
    for num in nums:
        xor_array ^= num
        
    for i in range(min_val, max_val + 1):
        xor_range ^= i
        
    return xor_array == xor_range
nums = [6, 8, 3, 5, 4, 7]
print(are_consecutive_xor(nums))  

Output

True
Updated on: 2025-01-20T18:26:42+05:30

6K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements