
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
Check for Contiguous Integers in an Array
A sequence of numbers is said to be contiguous if the numbers can be arranged in such a way that each number follows the previous one without any gaps. For example, [11,12,13,14] is a contiguous sequence because there are no missing numbers between the smallest and largest values.
In this article, we need to check if an array contains such contiguous integers, even when the duplicates are present. For instance, [11,12,13,13,14] should still be considered contiguous because the unique numbers are [11,12,13,14], which form a proper sequence without breaks.
The following are the example scenarios:
Scenario 1Input: [11,12,13,13,14] Output: True Explanation: The unique elements from the given array are [11,12,13,14]. i.e. the smallest number is 11 and the largest is 14. The range length(14 - 11 + 1 = 4) matches the unique elements, so the sequence is contiguous.Scenario 2
Input: [2,3,5,6,2,7] Output: False Explanation: The unique elements from the given array are [2,3,5,6,7]. i.e. the smallest number is 2 and the largest is 7. The range length(7 - 2 + 1 = 6), which does not matches the unique elements, so it is not contiguous.
Let's dive into the following example for getting a better understanding of checking whether the given array contains the contiguous elements, even when the duplicates are allowed.
Example 1
Let's look at the following example, where we are going to consider the input [11,12,13,13,14] along with duplicates.
def demo(arr): x = set(arr) a = min(x) b = max(x) return len(x) == (b - a + 1) arr = [11,12,13,13,14] print(demo(arr))
Following is the output of the above program:
True
Example 2
Let's look at the following example, where we are going to consider the input [2,3,5,6,2,7] along with duplicates and checking whether the given array contains the contiguous integers or not.
def demo(arr): x = set(arr) a = min(x) b = max(x) return len(x) == (b - a + 1) arr = [2,3,5,6,2,7] print(demo(arr))
Following is the output of the above program:
False
Example 3
In the following example, we are going to consider a single element and check whether the given array contains the contiguous integers or not.
def demo(array): x = set(array) a = min(x) b = max(x) return len(x) == (b - a + 1) array = [111] print(demo(array))
Following is the output of the above program:
True