Suppose we have an array of numbers called nums, it may have duplicate elements. We have to check whether it is a set of contiguous numbers or not.
So, if the input is like nums = [6, 8, 8, 3, 3, 3, 5, 4, 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 −
- sort the list nums
- for i in range 1 to size of nums - 1, do
- if nums[i] - nums[i-1] > 1, then
- return False
- if nums[i] - nums[i-1] > 1, then
- return True
Let us see the following implementation to get better understanding −
Example
def solve(nums): nums.sort() for i in range(1,len(nums)): if nums[i] - nums[i-1] > 1: return False return True nums = [6, 8, 8, 3, 3, 3, 5, 4, 4, 7] print(solve(nums))
Input
[6, 8, 8, 3, 3, 3, 5, 4, 4, 7]
Output
True