# 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.

To solve this, we will follow these steps −

• if size of nums < 1, then
• return False
• min_val := minimum of nums, max_val := maximum of nums
• if (max_val - min_val + 1) is same as size of nums , then
• for i in range 0 to size of nums, do
• if nums[i] < 0, then
• j:= -nums[i] - min_val
• otherwise,
• j := nums[i] - min_val
• if nums[j] > 0, then
• nums[j] := -nums[j]
• otherwise,
• return False
• return True
• return False

Let us see the following implementation to get better understanding −

## Example

Live Demo

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))

## Input

[6, 8, 3, 5, 4, 7]

## Output

True

Updated on: 30-Dec-2020

5K+ Views

##### Kickstart Your Career

Get certified by completing the course