Check if array contains contiguous integers with duplicates allowed
Given an array of n integers(duplicates allowed). Print “Yes” if it is a set of contiguous integers else print “No”.
Examples:
Input : arr[] = {5, 2, 3, 6, 4, 4, 6, 6}
Output : Yes
The elements form a contiguous set of integers
which is {2, 3, 4, 5, 6}.
Input : arr[] = {10, 14, 10, 12, 12, 13, 15}
Output : No
We have discussed different solutions for distinct elements in the below post.
Check if array elements are consecutive
Algorithm:
Step 1: Start
Step 2: Create a function of boolean return type name it as “areElementsContiguous” which takes integer array and integer value as input parameter.
Step 3: Sort the given array.
Step 4: Start a for loop form i=0 to i< length of the array.
a. check if the value of the current index – is the value of the previous index then return false
b. if came out of the loop and there is no such pair present in the array then return true.
Step 5: End
A simple solution is to first sort the array. Then traverse the array to check if all consecutive elements differ at most by one.
C++
#include <bits/stdc++.h>
using namespace std;
bool areElementsContiguous( int arr[], int n)
{
sort(arr, arr+n);
for ( int i = 1; i < n; i++)
if (arr[i] - arr[i-1] > 1)
return false ;
return true ;
}
int main()
{
int arr[] = { 5, 2, 3, 6,
4, 4, 6, 6 };
int n = sizeof (arr) / sizeof (arr[0]);
if (areElementsContiguous(arr, n))
cout << "Yes" ;
else
cout << "No" ;
return 0;
}
|
Java
import java.util.*;
class GFG {
static boolean areElementsContiguous( int arr[],
int n)
{
Arrays.sort(arr);
for ( int i = 1 ; i < n; i++)
if (arr[i] - arr[i- 1 ] > 1 )
return false ;
return true ;
}
public static void main(String[] args)
{
int arr[] = { 5 , 2 , 3 , 6 ,
4 , 4 , 6 , 6 };
int n = arr.length;
if (areElementsContiguous(arr, n))
System.out.println( "Yes" );
else
System.out.println( "No" );
}
}
|
Python3
def areElementsContiguous(arr, n):
arr.sort()
for i in range ( 1 ,n):
if (arr[i] - arr[i - 1 ] > 1 ) :
return 0
return 1
arr = [ 5 , 2 , 3 , 6 , 4 , 4 , 6 , 6 ]
n = len (arr)
if areElementsContiguous(arr, n): print ( "Yes" )
else : print ( "No" )
|
C#
using System;
class GFG {
static bool areElementsContiguous( int []arr,
int n)
{
Array.Sort(arr);
for ( int i = 1; i < n; i++)
if (arr[i] - arr[i - 1] > 1)
return false ;
return true ;
}
public static void Main()
{
int []arr = { 5, 2, 3, 6,
4, 4, 6, 6 };
int n = arr.Length;
if (areElementsContiguous(arr, n))
Console.WriteLine( "Yes" );
else
Console.WriteLine( "No" );
}
}
|
Javascript
<script>
function areElementsContiguous(arr, n)
{
arr.sort( function (a, b){ return a - b});
for (let i = 1; i < n; i++)
if (arr[i] - arr[i - 1] > 1)
return false ;
return true ;
}
let arr = [ 5, 2, 3, 6, 4, 4, 6, 6 ];
let n = arr.length;
if (areElementsContiguous(arr, n))
document.write( "Yes" );
else
document.write( "No" );
</script>
|
PHP
<?php
function areElementsContiguous( $arr , $n )
{
sort( $arr );
for ( $i = 1; $i < $n ; $i ++)
if ( $arr [ $i ] - $arr [ $i - 1] > 1)
return false;
return true;
}
$arr = array ( 5, 2, 3, 6,
4, 4, 6, 6 );
$n = sizeof( $arr );
if (areElementsContiguous( $arr , $n ))
echo "Yes" ;
else
echo "No" ;
?>
|
Time Complexity: O(n Log n)
Auxiliary Space: O(1)
Auxiliary Space is constant because we are not using any extra space.
Another Approach:
If we can find the minimum element and maximum element that are present in the array and use the below procedure then we can say that the array contains contiguous elements or not.
PROCEDURE :-
1) Store the elements in unordered set (So as to maintain the Time complexity of the problem i.e. O(n) )
2) Find the minimum element present in the array and store it in a variable say min_ele.
3) Find the maximum element present in the array and store it in a variable say max_ele.
4) Now just think a little bit we can notice that if we Subtract the min_ele from the max_ele and add 1 to the result.
5) If the final result is equal to the size of the set then in that case we can say that the given array contains contiguous elements.
Lets take a example to understand the above procedure.
Lets say that after storing the value in the unordered set we have the values inside it from 1 to 10 (1,2,3,4,5,6,7,8,9,10). The actual order inside the unordered set is not like this I have just taken it to for easier understanding.
From the example above we can clearly say that the maximum element present in the set is 10 and minimum element present in the set is 1.
Subtracting the minimum element from the maximum element we get 9 as the result(10-1=9).
Now when we add 1 to the result and compare it with the size of the unordered set then we can say that the they are equal. (9+1=10 which is equal to the size of the unordered set).
Hence the function will return True.
Now just imagine if one of the element is not present in the unordered set (say 5) then in that case the size of unordered set is 9 then in that case 10 which is final result is not equal to the size of the unordered set. And hence the function will return False.
The Implementation of the above method is :-
C++
#include <bits/stdc++.h>
using namespace std;
bool areElementsContiguous( int arr[], int n)
{
unordered_set< int > s(arr, arr + n);
int set_size = s.size();
int max = *max_element(arr, arr + n);
int min = *min_element(arr, arr + n);
int result = max - min + 1;
if (result != set_size)
return false ;
return true ;
}
int main()
{
int arr[] = { 5, 2, 3, 6, 4, 4, 6, 6 };
int n = sizeof (arr) / sizeof (arr[0]);
if (areElementsContiguous(arr, n))
cout << "Yes" ;
else
cout << "No" ;
return 0;
}
|
Java
import java.util.*;
class GFG {
public static boolean
areElementsContiguous(ArrayList<Integer> arr, int n)
{
HashSet<Integer> s = new HashSet<Integer>();
for ( int i = 0 ; i < n; ++i)
s.add(arr.get(i));
int set_size = s.size();
int max = Collections.max(arr);
int min = Collections.min(arr);
int result = max - min + 1 ;
if (result != set_size)
return false ;
return true ;
}
public static void main(String[] args)
{
ArrayList<Integer> arr = new ArrayList<Integer>(
Arrays.asList( 5 , 2 , 3 , 6 , 4 , 4 , 6 , 6 ));
int n = arr.size();
if (areElementsContiguous(arr, n))
System.out.print( "Yes" );
else
System.out.print( "No" );
}
}
|
Python3
def areElementsContiguous(arr, n):
s = set (arr)
set_size = len (s)
maxi = max (arr)
mini = min (arr)
result = maxi - mini + 1
if result ! = set_size:
return False
return True
if __name__ = = "__main__" :
arr = [ 5 , 2 , 3 , 6 , 4 , 4 , 6 , 6 ]
n = len (arr)
if areElementsContiguous(arr, n):
print ( "Yes" )
else :
print ( "No" )
|
C#
using System;
using System.Linq;
using System.Collections.Generic;
public class GFG {
static bool AreElementsContiguous( int [] arr)
{
HashSet< int > s = new HashSet< int >(arr);
int setSize = s.Count;
int max = arr.Max();
int min = arr.Min();
int result = max - min + 1;
if (result != setSize) {
return false ;
}
return true ;
}
static void Main( string [] args)
{
int [] arr = { 5, 2, 3, 6, 4, 4, 6, 6 };
if (AreElementsContiguous(arr)) {
Console.WriteLine( "Yes" );
}
else {
Console.WriteLine( "No" );
}
}
}
|
Javascript
function areElementsContiguous(arr) {
var s = new Set(arr);
var setSize = s.size;
var maxi = Math.max.apply( null , arr);
var mini = Math.min.apply( null , arr);
var result = maxi - mini + 1;
if (result !== setSize) {
return false ;
}
return true ;
}
( function (){
var arr = [5, 2, 3, 6, 4, 4, 6, 6];
if (areElementsContiguous(arr)) {
console.log( "Yes" );
} else {
console.log( "No" );
}
})();
|
Time Complexity: O(n)
Auxiliary Space: O(n)
Efficient solution using visited array
1) Find the minimum and maximum elements.
2) Create a visited array of size max-min + 1. Initialize this array as false.
3) Traverse the given array and mark visited[arr[i] – min] as true for every element arr[i].
4) Traverse visited array and return true if all values are true. Else return false.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
bool areElementsContiguous( int arr[], int n)
{
int max = *max_element(arr, arr + n);
int min = *min_element(arr, arr + n);
int m = max - min + 1;
if (m > n)
return false ;
bool visited[m];
memset (visited, false , sizeof (visited));
for ( int i=0; i<n; i++)
visited[arr[i] - min] = true ;
for ( int i=0; i<m; i++)
if (visited[i] == false )
return false ;
return true ;
}
int main()
{
int arr[] = { 5, 2, 3, 6,
4, 4, 6, 6 };
int n = sizeof (arr) / sizeof (arr[0]);
if (areElementsContiguous(arr, n))
cout << "Yes" ;
else
cout << "No" ;
return 0;
}
|
Java
import java.util.*;
class GFG {
static boolean areElementsContiguous( int arr[],
int n)
{
int max = Integer.MIN_VALUE;
int min = Integer.MAX_VALUE;
for ( int i = 0 ; i < n; i++)
{
max = Math.max(max, arr[i]);
min = Math.min(min, arr[i]);
}
int m = max - min + 1 ;
if (m > n)
return false ;
boolean visited[] = new boolean [n];
for ( int i = 0 ; i < n; i++)
visited[arr[i] - min] = true ;
for ( int i = 0 ; i < m; i++)
if (visited[i] == false )
return false ;
return true ;
}
public static void main(String[] args)
{
int arr[] = { 5 , 2 , 3 , 6 ,
4 , 4 , 6 , 6 };
int n = arr.length;
if (areElementsContiguous(arr, n))
System.out.println( "Yes" );
else
System.out.println( "No" );
}
}
|
Python3
def areElementsContiguous(arr, n):
max1 = max (arr)
min1 = min (arr)
m = max1 - min1 + 1
if (m > n):
return False
visited = [ 0 ] * m
for i in range ( 0 ,n) :
visited[arr[i] - min1] = True
for i in range ( 0 , m):
if (visited[i] = = False ):
return False
return True
arr = [ 5 , 2 , 3 , 6 , 4 , 4 , 6 , 6 ]
n = len (arr)
if (areElementsContiguous(arr, n)):
print ( "Yes" )
else :
print ( "No" )
|
C#
using System;
class GFG {
static bool areElementsContiguous(
int []arr, int n)
{
int max = int .MinValue;
int min = int .MaxValue;
for ( int i = 0; i < n; i++)
{
max = Math.Max(max, arr[i]);
min = Math.Min(min, arr[i]);
}
int m = max - min + 1;
if (m > n)
return false ;
bool []visited = new bool [n];
for ( int i = 0; i < n; i++)
visited[arr[i] - min] = true ;
for ( int i = 0; i < m; i++)
if (visited[i] == false )
return false ;
return true ;
}
public static void Main()
{
int []arr = { 5, 2, 3, 6,
4, 4, 6, 6 };
int n = arr.Length;
if (areElementsContiguous(arr, n))
Console.Write( "Yes" );
else
Console.Write( "No" );
}
}
|
Javascript
<script>
function areElementsContiguous(arr, n)
{
let max = Number.MIN_VALUE;
let min = Number.MAX_VALUE;
for (let i = 0; i < n; i++)
{
max = Math.max(max, arr[i]);
min = Math.min(min, arr[i]);
}
let m = max - min + 1;
if (m > n)
return false ;
let visited = new Array(n);
visited.fill( false );
for (let i = 0; i < n; i++)
visited[arr[i] - min] = true ;
for (let i = 0; i < m; i++)
if (visited[i] == false )
return false ;
return true ;
}
let arr = [ 5, 2, 3, 6, 4, 4, 6, 6 ];
let n = arr.length;
if (areElementsContiguous(arr, n))
document.write( "Yes" );
else
document.write( "No" );
</script>
|
Time Complexity: O(n)
Auxiliary Space: (m)
Efficient solution using the hash table:
Insert all the elements in the hash table. Now pick the first element and keep on incrementing in its value by 1 till you find a value not present in the hash table. Again pick the first element and keep on decrementing in its value by 1 till you find a value not present in the hash table. Get the count of elements (obtained by this process) that are present in the hash table. If the count equals hash size print “Yes” else “No”.
C++
#include <bits/stdc++.h>
using namespace std;
bool areElementsContiguous( int arr[], int n)
{
unordered_set< int > us;
for ( int i = 0; i < n; i++)
us.insert(arr[i]);
int count = 1;
int curr_ele = arr[0] - 1;
while (us.find(curr_ele) != us.end()) {
count++;
curr_ele--;
}
curr_ele = arr[0] + 1;
while (us.find(curr_ele) != us.end()) {
count++;
curr_ele++;
}
return (count == ( int )(us.size()));
}
int main()
{
int arr[] = { 5, 2, 3, 6, 4, 4, 6, 6 };
int n = sizeof (arr) / sizeof (arr[0]);
if (areElementsContiguous(arr, n))
cout << "Yes" ;
else
cout << "No" ;
return 0;
}
|
Java
import java.io.*;
import java.util.*;
class GFG {
static Boolean areElementsContiguous( int arr[], int n)
{
HashSet<Integer> us = new HashSet<Integer>();
for ( int i = 0 ; i < n; i++)
us.add(arr[i]);
int count = 1 ;
int curr_ele = arr[ 0 ] - 1 ;
while (us.contains(curr_ele) == true ) {
count++;
curr_ele--;
}
curr_ele = arr[ 0 ] + 1 ;
while (us.contains(curr_ele) == true ) {
count++;
curr_ele++;
}
return (count == (us.size()));
}
public static void main(String[] args)
{
int arr[] = { 5 , 2 , 3 , 6 , 4 , 4 , 6 , 6 };
int n = arr.length;
if (areElementsContiguous(arr, n))
System.out.println( "Yes" );
else
System.out.println( "No" );
}
}
|
Python
def areElementsContiguous(arr):
us = set ()
for i in arr: us.add(i)
count = 1
curr_ele = arr[ 0 ] - 1
while curr_ele in us:
count + = 1
curr_ele - = 1
curr_ele = arr[ 0 ] + 1
while curr_ele in us:
count + = 1
curr_ele + = 1
return (count = = len (us))
arr = [ 5 , 2 , 3 , 6 , 4 , 4 , 6 , 6 ]
if areElementsContiguous(arr): print ( "Yes" )
else : print ( "No" )
|
C#
using System;
using System.Collections.Generic;
public class GFG
{
public static bool ? areElementsContiguous( int [] arr, int n)
{
HashSet< int > us = new HashSet< int >();
for ( int i = 0; i < n; i++)
{
us.Add(arr[i]);
}
int count = 1;
int curr_ele = arr[0] - 1;
while (us.Contains(curr_ele) == true )
{
count++;
curr_ele--;
}
curr_ele = arr[0] + 1;
while (us.Contains(curr_ele) == true )
{
count++;
curr_ele++;
}
return (count == (us.Count));
}
public static void Main( string [] args)
{
int [] arr = new int [] {5, 2, 3, 6, 4, 4, 6, 6};
int n = arr.Length;
if (areElementsContiguous(arr, n).Value)
{
Console.WriteLine( "Yes" );
}
else
{
Console.WriteLine( "No" );
}
}
}
|
Javascript
<script>
function areElementsContiguous(arr, n)
{
var us = new Set();
for ( var i = 0; i < n; i++)
us.add(arr[i]);
var count = 1;
var curr_ele = arr[0] - 1;
while (us.has(curr_ele)) {
count++;
curr_ele--;
}
curr_ele = arr[0] + 1;
while (us.has(curr_ele)) {
count++;
curr_ele++;
}
return (count == (us.size));
}
var arr = [5, 2, 3, 6, 4, 4, 6, 6];
var n = arr.length;
if (areElementsContiguous(arr, n))
document.write( "Yes" );
else
document.write( "No" );
</script>
|
Time Complexity: O(n).
Auxiliary Space: O(n).
ANOTHER APPROACH USING HASH SET:
Intuition:
- We declare a HashSet to store the elements in the array uniquely.
- Then we traverse the array by maintaining a longest-streak and current-streak pointer.
- While traversing if set doesn’t contains (num-1) element, then we run a while loop till (current-element+1) elements are present in the set and we increase the value of current-streak by 1.
- after the while loop is terminated ,we update the longest-streak variable by comparing it with current-streak and keeps the maximum value with it.
- Atlast if the longest-streak is equal to the size of set then we can say that array contains contiguous elements and return true,else return false.
Implementation:
C++
#include <bits/stdc++.h>
using namespace std;
bool areElementsContiguous( int arr[], int n)
{
unordered_set< int > set;
for ( int i = 0; i < n; i++)
set.insert(arr[i]);
int longestst = 0;
for ( int i : set) {
if (set.find(i - 1) == set.end()) {
int curnum = i;
int curst = 1;
while (set.find(curnum + 1) != set.end()) {
curst++;
curnum++;
}
longestst = max(longestst, curst);
}
}
return set.size() == longestst;
}
int main()
{
int arr[] = { 5, 2, 3, 6, 4, 4, 6, 6 };
int n = sizeof (arr) / sizeof (arr[0]);
if (areElementsContiguous(arr, n))
cout << "Yes" ;
else
cout << "No" ;
return 0;
}
|
Java
import java.io.*;
import java.util.*;
class GFG {
public static boolean areElementsContiguous( int arr[],
int n)
{
Set<Integer> set = new HashSet<>();
for ( int i : arr)
set.add(i);
int longestst = 0 ;
for ( int i : set) {
if (!set.contains(i - 1 )) {
int curnum = i;
int curst = 1 ;
while (set.contains(curnum + 1 )) {
curst++;
curnum++;
}
longestst = Math.max(longestst, curst);
}
}
return set.size() == longestst;
}
public static void main(String[] args)
{
int arr[] = { 5 , 2 , 3 , 6 , 4 , 4 , 6 , 6 };
int n = arr.length;
if (areElementsContiguous(arr, n))
System.out.println( "Yes" );
else
System.out.println( "No" );
}
}
|
Python3
def are_elements_contiguous(arr):
num_set = set (arr)
longest_streak = 0
for num in num_set:
if num - 1 not in num_set:
current_num = num
current_streak = 1
while current_num + 1 in num_set:
current_streak + = 1
current_num + = 1
longest_streak = max (longest_streak, current_streak)
return len (num_set) = = longest_streak
arr = [ 5 , 2 , 3 , 6 , 4 , 4 , 6 , 6 ]
if are_elements_contiguous(arr):
print ( "Yes" )
else :
print ( "No" )
|
C#
using System;
using System.Collections.Generic;
class Program {
static bool AreElementsContiguous( int [] arr)
{
HashSet< int > set = new HashSet< int >();
foreach ( int num in arr) { set .Add(num); }
int longestStreak = 0;
foreach ( int num in set )
{
if (! set .Contains(num - 1)) {
int currentNum = num;
int currentStreak = 1;
while ( set .Contains(currentNum + 1)) {
currentStreak++;
currentNum++;
}
longestStreak = Math.Max(longestStreak,
currentStreak);
}
}
return set .Count == longestStreak;
}
static void Main()
{
int [] arr = { 5, 2, 3, 6, 4, 4, 6, 6 };
if (AreElementsContiguous(arr)) {
Console.WriteLine(
"Yes" );
}
else {
Console.WriteLine(
"No" );
}
}
}
|
Javascript
function areElementsContiguous(arr) {
let set = new Set();
for (let i = 0; i < arr.length; i++) {
set.add(arr[i]);
}
let longestst = 0;
for (let i of set) {
if (!set.has(i - 1)) {
let curnum = i;
let curst = 1;
while (set.has(curnum + 1)) {
curst++;
curnum++;
}
longestst = Math.max(longestst, curst);
}
}
return set.size === longestst;
}
const arr = [5, 2, 3, 6, 4, 4, 6, 6];
if (areElementsContiguous(arr)) {
console.log( "Yes" );
} else {
console.log( "No" );
}
|
Time Complexity: O(N) since we traversing the array once.
Space Complexity: O(N) since we using a HashSet to store elements uniquely.
This method requires only one traversal of the given array. It traverses the hash table after array traversal (the hash table contains only distinct elements).
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...