
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Check If Array Contains Contiguous Integers with Duplicates Allowed in Python
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
Advertisements