Check if array contains contiguous integers with duplicates allowed
Last Updated :
21 May, 2024
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++
// Sorting based C++ implementation
// to check whether the array
// contains a set of contiguous
// integers
#include <bits/stdc++.h>
using namespace std;
// function to check whether
// the array contains a set
// of contiguous integers
bool areElementsContiguous(int arr[], int n)
{
// Sort the array
sort(arr, arr+n);
// After sorting, check if
// current element is either
// same as previous or is
// one more.
for (int i = 1; i < n; i++)
if (arr[i] - arr[i-1] > 1)
return false;
return true;
}
// Driver program to test above
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
// Sorting based Java implementation
// to check whether the array
// contains a set of contiguous
// integers
import java.util.*;
class GFG {
// function to check whether
// the array contains a set
// of contiguous integers
static boolean areElementsContiguous(int arr[],
int n)
{
// Sort the array
Arrays.sort(arr);
// After sorting, check if
// current element is either
// same as previous or is
// one more.
for (int i = 1; i < n; i++)
if (arr[i] - arr[i-1] > 1)
return false;
return true;
}
/* Driver program to test above function */
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");
}
}
// This code is contributed by Arnav Kr. Mandal.
Python
# Sorting based Python implementation
# to check whether the array
# contains a set of contiguous integers
def areElementsContiguous(arr, n):
# Sort the array
arr.sort()
# After sorting, check if
# current element is either
# same as previous or is
# one more.
for i in range(1,n):
if (arr[i] - arr[i-1] > 1) :
return 0
return 1
# Driver code
arr = [ 5, 2, 3, 6, 4, 4, 6, 6 ]
n = len(arr)
if areElementsContiguous(arr, n): print("Yes")
else: print("No")
# This code is contributed by 'Ansu Kumari'.
C#
// Sorting based C# implementation
// to check whether the array
// contains a set of contiguous
// integers
using System;
class GFG {
// function to check whether
// the array contains a set
// of contiguous integers
static bool areElementsContiguous(int []arr,
int n)
{
// Sort the array
Array.Sort(arr);
// After sorting, check if
// current element is either
// same as previous or is
// one more.
for (int i = 1; i < n; i++)
if (arr[i] - arr[i - 1] > 1)
return false;
return true;
}
// Driver program
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");
}
}
// This code is contributed by Vt_m.
JavaScript
<script>
// Sorting based Javascript implementation
// to check whether the array
// contains a set of contiguous
// integers
// function to check whether
// the array contains a set
// of contiguous integers
function areElementsContiguous(arr, n)
{
// Sort the array
arr.sort(function(a, b){return a - b});
// After sorting, check if
// current element is either
// same as previous or is
// one more.
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");
// This code is contributed by rameshtravel07.
</script>
PHP
<?php
// Sorting based PHP implementation to check
// whether the array contains a set of contiguous
// integers
// function to check whether the array contains
// a set of contiguous integers
function areElementsContiguous($arr, $n)
{
// Sort the array
sort($arr);
// After sorting, check if current element
// is either same as previous or is one more.
for ($i = 1; $i < $n; $i++)
if ($arr[$i] - $arr[$i - 1] > 1)
return false;
return true;
}
// Driver Code
$arr = array( 5, 2, 3, 6,
4, 4, 6, 6 );
$n = sizeof($arr);
if (areElementsContiguous($arr, $n))
echo "Yes";
else
echo "No";
// This code is contributed by ajit
?>
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++
// C++ implementation to check whether the array contains a
// set of contiguous integers
#include <bits/stdc++.h>
using namespace std;
// function to check whether the array contains a set of
// contiguous integers
bool areElementsContiguous(int arr[], int n)
{
// Declaring and Initialising the set simultaneously
unordered_set<int> s(arr, arr + n);
// Finding the size of the unordered set
int set_size = s.size();
// Find maximum and minimum elements.
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;
}
// Driver program
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;
}
// This code is contributed by Aditya Kumar (adityakumar129)
Java
// JAVA implementation to check whether the array contains a
// set of contiguous integers
import java.util.*;
class GFG {
// function to check whether the array contains a set of
// contiguous integers
public static boolean
areElementsContiguous(ArrayList<Integer> arr, int n)
{
// Declaring and Initialising the set simultaneously
HashSet<Integer> s = new HashSet<Integer>();
for (int i = 0; i < n; ++i)
s.add(arr.get(i));
// Finding the size of the unordered set
int set_size = s.size();
// Find maximum and minimum elements.
int max = Collections.max(arr);
int min = Collections.min(arr);
int result = max - min + 1;
if (result != set_size)
return false;
return true;
}
// Driver program
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");
}
}
// This code is contributed by Taranpreet
Python
# Python3 implementation to check whether the array contains a
# set of contiguous integers
# function to check whether the array contains a set of
# contiguous integers
def areElementsContiguous(arr, n):
# Declaring and Initialising the set simultaneously
s = set(arr)
# Finding the size of the set
set_size = len(s)
# Find maximum and minimum elements.
maxi = max(arr)
mini = min(arr)
result = maxi - mini + 1
if result != set_size:
return False
return True
# Driver program
if __name__ == "__main__":
arr = [5, 2, 3, 6, 4, 4, 6, 6]
n = len(arr)
if areElementsContiguous(arr, n):
print("Yes")
else:
print("No")
# This code is contributed by divyansh2212
C#
using System;
using System.Linq;
using System.Collections.Generic;
public class GFG {
static bool AreElementsContiguous(int[] arr)
{
// Declaring and Initializing the HashSet
HashSet<int> s = new HashSet<int>(arr);
// Finding the size of the HashSet
int setSize = s.Count;
// Finding the maximum and minimum elements
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");
}
}
}
// This code is contributed by Shivam Tiwari
JavaScript
// function to check whether the array contains a set of
// contiguous integers
function areElementsContiguous(arr) {
// Declaring and Initialising the set simultaneously
var s = new Set(arr);
// Finding the size of the set
var setSize = s.size;
// Find maximum and minimum elements.
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;
}
// Driver program
(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++
// C++ implementation to
// check whether the array
// contains a set of
// contiguous integers
#include <bits/stdc++.h>
using namespace std;
// function to check
// whether the array
// contains a set of
// contiguous integers
bool areElementsContiguous(int arr[], int n)
{
// Find maximum and
// minimum elements.
int max = *max_element(arr, arr + n);
int min = *min_element(arr, arr + n);
int m = max - min + 1;
// There should be at least
// m elements in array to
// make them contiguous.
if (m > n)
return false;
// Create a visited array
// and initialize false.
bool visited[m];
memset(visited, false, sizeof(visited));
// Mark elements as true.
for (int i=0; i<n; i++)
visited[arr[i] - min] = true;
// If any element is not
// marked, all elements
// are not contiguous.
for (int i=0; i<m; i++)
if (visited[i] == false)
return false;
return true;
}
// Driver program
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
// Java implementation to
// check whether the array
// contains a set of
// contiguous integers
import java.util.*;
class GFG {
// function to check
// whether the array
// contains a set of
// contiguous integers
static boolean areElementsContiguous(int arr[],
int n)
{
// Find maximum and
// minimum elements.
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;
// There should be at least
// m elements in array to
// make them contiguous.
if (m > n)
return false;
// Create a visited array
// and initialize false.
boolean visited[] = new boolean[n];
// Mark elements as true.
for (int i = 0; i < n; i++)
visited[arr[i] - min] = true;
// If any element is not
// marked, all elements
// are not contiguous.
for (int i = 0; i < m; i++)
if (visited[i] == false)
return false;
return true;
}
/* Driver program */
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
# Python3 implementation to
# check whether the array
# contains a set of
# contiguous integers
# function to check
# whether the array
# contains a set of
# contiguous integers
def areElementsContiguous(arr, n):
# Find maximum and
# minimum elements.
max1 = max(arr)
min1 = min(arr)
m = max1 - min1 + 1
# There should be at least
# m elements in array to
# make them contiguous.
if (m > n):
return False
# Create a visited array
# and initialize false
visited = [0] * m
# Mark elements as true.
for i in range(0,n) :
visited[arr[i] - min1] = True
# If any element is not
# marked, all elements
# are not contiguous.
for i in range(0, m):
if (visited[i] == False):
return False
return True
# Driver program
arr = [5, 2, 3, 6, 4, 4, 6, 6 ]
n = len(arr)
if (areElementsContiguous(arr, n)):
print("Yes")
else:
print("No")
# This code is contributed by Smitha Dinesh Semwal
C#
// C# implementation to check whether
// the array contains a set of
// contiguous integers
using System;
class GFG {
// function to check whether the
// array contains a set of
// contiguous integers
static bool areElementsContiguous(
int []arr, int n)
{
// Find maximum and
// minimum elements.
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;
// There should be at least
// m elements in array to
// make them contiguous.
if (m > n)
return false;
// Create a visited array
// and initialize false.
bool []visited = new bool[n];
// Mark elements as true.
for (int i = 0; i < n; i++)
visited[arr[i] - min] = true;
// If any element is not
// marked, all elements
// are not contiguous.
for (int i = 0; i < m; i++)
if (visited[i] == false)
return false;
return true;
}
/* Driver program */
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");
}
}
// This code is contributed by nitin mittal.
JavaScript
<script>
// Javascript implementation to
// check whether the array
// contains a set of
// contiguous integers
// function to check whether the
// array contains a set of
// contiguous integers
function areElementsContiguous(arr, n)
{
// Find maximum and
// minimum elements.
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;
// There should be at least
// m elements in array to
// make them contiguous.
if (m > n)
return false;
// Create a visited array
// and initialize false.
let visited = new Array(n);
visited.fill(false);
// Mark elements as true.
for (let i = 0; i < n; i++)
visited[arr[i] - min] = true;
// If any element is not
// marked, all elements
// are not contiguous.
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++
// C++ implementation to check whether the array
// contains a set of contiguous integers
#include <bits/stdc++.h>
using namespace std;
// Function to check whether the array contains
// a set of contiguous integers
bool areElementsContiguous(int arr[], int n)
{
// Storing elements of 'arr[]' in a hash
// table 'us'
unordered_set<int> us;
for (int i = 0; i < n; i++)
us.insert(arr[i]);
// as arr[0] is present in 'us'
int count = 1;
// starting with previous smaller element
// of arr[0]
int curr_ele = arr[0] - 1;
// if 'curr_ele' is present in 'us'
while (us.find(curr_ele) != us.end()) {
// increment count
count++;
// update 'curr_ele"
curr_ele--;
}
// starting with next greater element
// of arr[0]
curr_ele = arr[0] + 1;
// if 'curr_ele' is present in 'us'
while (us.find(curr_ele) != us.end()) {
// increment count
count++;
// update 'curr_ele"
curr_ele++;
}
// returns true if array contains a set of
// contiguous integers else returns false
return (count == (int)(us.size()));
}
// Driver program to test above
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
// Java implementation to check whether the array
// contains a set of contiguous integers
import java.io.*;
import java.util.*;
class GFG {
// Function to check whether the array
// contains a set of contiguous integers
static Boolean areElementsContiguous(int arr[], int n)
{
// Storing elements of 'arr[]' in
// a hash table 'us'
HashSet<Integer> us = new HashSet<Integer>();
for (int i = 0; i < n; i++)
us.add(arr[i]);
// As arr[0] is present in 'us'
int count = 1;
// Starting with previous smaller
// element of arr[0]
int curr_ele = arr[0] - 1;
// If 'curr_ele' is present in 'us'
while (us.contains(curr_ele) == true) {
// increment count
count++;
// update 'curr_ele"
curr_ele--;
}
// Starting with next greater
// element of arr[0]
curr_ele = arr[0] + 1;
// If 'curr_ele' is present in 'us'
while (us.contains(curr_ele) == true) {
// increment count
count++;
// update 'curr_ele"
curr_ele++;
}
// Returns true if array contains a set of
// contiguous integers else returns false
return (count == (us.size()));
}
// Driver Code
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");
}
}
// This code is contributed by 'Gitanjali'.
Python
# Python implementation to check whether the array
# contains a set of contiguous integers
# Function to check whether the array
# contains a set of contiguous integers
def areElementsContiguous(arr):
# Storing elements of 'arr[]' in a hash table 'us'
us = set()
for i in arr: us.add(i)
# As arr[0] is present in 'us'
count = 1
# Starting with previous smaller element of arr[0]
curr_ele = arr[0] - 1
# If 'curr_ele' is present in 'us'
while curr_ele in us:
# Increment count
count += 1
# Update 'curr_ele"
curr_ele -= 1
# Starting with next greater element of arr[0]
curr_ele = arr[0] + 1
# If 'curr_ele' is present in 'us'
while curr_ele in us:
# Increment count
count += 1
# Update 'curr_ele"
curr_ele += 1
# Returns true if array contains a set of
# contiguous integers else returns false
return (count == len(us))
# Driver code
arr = [ 5, 2, 3, 6, 4, 4, 6, 6 ]
if areElementsContiguous(arr): print("Yes")
else: print("No")
# This code is contributed by 'Ansu Kumari'
C#
using System;
using System.Collections.Generic;
// c# implementation to check whether the array
// contains a set of contiguous integers
public class GFG
{
// Function to check whether the array
// contains a set of contiguous integers
public static bool? areElementsContiguous(int[] arr, int n)
{
// Storing elements of 'arr[]' in
// a hash table 'us'
HashSet<int> us = new HashSet<int>();
for (int i = 0; i < n; i++)
{
us.Add(arr[i]);
}
// As arr[0] is present in 'us'
int count = 1;
// Starting with previous smaller
// element of arr[0]
int curr_ele = arr[0] - 1;
// If 'curr_ele' is present in 'us'
while (us.Contains(curr_ele) == true)
{
// increment count
count++;
// update 'curr_ele"
curr_ele--;
}
// Starting with next greater
// element of arr[0]
curr_ele = arr[0] + 1;
// If 'curr_ele' is present in 'us'
while (us.Contains(curr_ele) == true)
{
// increment count
count++;
// update 'curr_ele"
curr_ele++;
}
// Returns true if array contains a set of
// contiguous integers else returns false
return (count == (us.Count));
}
// Driver Code
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");
}
}
}
// This code is contributed by Shrikant13
JavaScript
<script>
// Javascript implementation to check whether the array
// contains a set of contiguous integers
// Function to check whether the array contains
// a set of contiguous integers
function areElementsContiguous(arr, n)
{
// Storing elements of 'arr[]' in a hash
// table 'us'
var us = new Set();
for (var i = 0; i < n; i++)
us.add(arr[i]);
// as arr[0] is present in 'us'
var count = 1;
// starting with previous smaller element
// of arr[0]
var curr_ele = arr[0] - 1;
// if 'curr_ele' is present in 'us'
while (us.has(curr_ele)) {
// increment count
count++;
// update 'curr_ele"
curr_ele--;
}
// starting with next greater element
// of arr[0]
curr_ele = arr[0] + 1;
// if 'curr_ele' is present in 'us'
while (us.has(curr_ele)) {
// increment count
count++;
// update 'curr_ele"
curr_ele++;
}
// returns true if array contains a set of
// contiguous integers else returns false
return (count == (us.size));
}
// Driver program to test above
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");
// This code is contributed by rutvik_56.
</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.
- At last 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;
// Function to check if array contains contiguous elements
bool areElementsContiguous(int arr[], int n)
{
// Create a set to store unique elements from the array
unordered_set<int> set;
// Insert all elements into the set
for (int i = 0; i < n; i++)
set.insert(arr[i]);
// Initialize the variable to store the length of the longest contiguous subsequence
int longestst = 0;
// Iterate through the set
for (int i : set) {
// If the previous element (i-1) is not in the set, then it can be the start of a subsequence
if (set.find(i - 1) == set.end()) {
int curnum = i;
int curst = 1;
// Count the length of the current contiguous subsequence
while (set.find(curnum + 1) != set.end()) {
curst++;
curnum++;
}
// Update the longest contiguous subsequence length
longestst = max(longestst, curst);
}
}
// If the size of the set is equal to the length of the longest contiguous subsequence, return true
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"; // If array contains contiguous elements
else
cout << "No"; // If array doesn't contain contiguous elements
return 0;
}
Java
// Java program to check if array contains contiguous
// elements.
import java.io.*;
import java.util.*;
class GFG {
public static boolean areElementsContiguous(int arr[],
int n)
{
// Complete the function
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");
}
}
// This code is contributed by Raunak Singh
Python
def are_elements_contiguous(arr):
# Create a set to store unique elements from the array
num_set = set(arr)
# Initialize the variable to store the length of the longest contiguous subsequence
longest_streak = 0
# Iterate through the set
for num in num_set:
# If the previous element (num-1) is not in the set, then it can be the start of a subsequence
if num - 1 not in num_set:
current_num = num
current_streak = 1
# Count the length of the current contiguous subsequence
while current_num + 1 in num_set:
current_streak += 1
current_num += 1
# Update the longest contiguous subsequence length
longest_streak = max(longest_streak, current_streak)
# If the size of the set is equal to the length of the longest contiguous subsequence, return True
return len(num_set) == longest_streak
# Driver code
arr = [5, 2, 3, 6, 4, 4, 6, 6]
if are_elements_contiguous(arr):
print("Yes") # If the array contains contiguous elements
else:
print("No") # If the array doesn't contain contiguous elements
C#
using System;
using System.Collections.Generic;
class Program {
// Function to check if array contains contiguous
// elements
static bool AreElementsContiguous(int[] arr)
{
// Create a HashSet to store unique elements from
// the array
HashSet<int> set = new HashSet<int>();
// Insert all elements into the HashSet
foreach(int num in arr) { set.Add(num); }
// Initialize the variable to store the length of
// the longest contiguous subsequence
int longestStreak = 0;
// Iterate through the HashSet
foreach(int num in set)
{
// If the previous element (num - 1) is not in
// the HashSet, it can be the start of a
// subsequence
if (!set.Contains(num - 1)) {
int currentNum = num;
int currentStreak = 1;
// Count the length of the current
// contiguous subsequence
while (set.Contains(currentNum + 1)) {
currentStreak++;
currentNum++;
}
// Update the longest contiguous subsequence
// length
longestStreak = Math.Max(longestStreak,
currentStreak);
}
}
// If the size of the HashSet is equal to the length
// of the longest contiguous subsequence, return
// true
return set.Count == longestStreak;
}
static void Main()
{
int[] arr = { 5, 2, 3, 6, 4, 4, 6, 6 };
if (AreElementsContiguous(arr)) {
Console.WriteLine(
"Yes"); // If the array contains contiguous
// elements
}
else {
Console.WriteLine(
"No"); // If the array doesn't contain
// contiguous elements
}
}
}
JavaScript
// Function to check if array contains contiguous elements
function areElementsContiguous(arr) {
// Create a Set to store unique elements from the array
let set = new Set();
// Insert all elements into the Set
for (let i = 0; i < arr.length; i++) {
set.add(arr[i]);
}
// Initialize the variable to store the length of the longest contiguous subsequence
let longestst = 0;
// Iterate through the Set
for (let i of set) {
// If the previous element (i-1) is not in the Set, then it can be the start of a subsequence
if (!set.has(i - 1)) {
let curnum = i;
let curst = 1;
// Count the length of the current contiguous subsequence
while (set.has(curnum + 1)) {
curst++;
curnum++;
}
// Update the longest contiguous subsequence length
longestst = Math.max(longestst, curst);
}
}
// If the size of the Set is equal to the length of the longest contiguous subsequence, return true
return set.size === longestst;
}
// Main function
const arr = [5, 2, 3, 6, 4, 4, 6, 6];
if (areElementsContiguous(arr)) {
console.log("Yes"); // If array contains contiguous elements
} else {
console.log("No"); // If array doesn't contain contiguous elements
}
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).
Similar Reads
Check for Array Contains Duplicate III
Given an integer array arr[] and two integers indexDifference and valueDifference, find a pair of indices (i, j) such that: i != jabs(i - j) <= indexDifferenceabs(arr[i] - arr[j]) <= valueDifferenceReturn true if such a pair exists, false otherwise. Example: Input: arr = [1,2,3,1], indexDiffer
6 min read
Check if array contains duplicates
Given an integer array arr[], check if the array contains any duplicate value.Examples:Input: arr[] = {4, 5, 6, 4}Output: trueExplanation: 4 is the duplicate value.Input: arr[] = {1, 2, 3, 4}Output: falseExplanation: All values are distinct.Table of Content[Naive Approach] By using two nested loops
11 min read
Check if it is possible to construct an array with the given conditions
Given integers N and K and an array A[] of M integers. The task is to check if it is possible to construct an array of size N such that- All the K consecutive elements of the array are distinct.Considering 1-based indexing, the integer i can be used A[i] times to construct the array.Note that sum of
9 min read
Check if an array contains all elements of a given range
An array containing positive elements is given. 'A' and 'B' are two numbers defining a range. Write a function to check if the array contains all elements in the given range. Examples : Input : arr[] = {1 4 5 2 7 8 3} A : 2, B : 5Output : YesInput : arr[] = {1 4 5 2 7 8 3} A : 2, B : 6Output : NoRec
15+ min read
Check if an array contains only one distinct element
Given an array arr[] of size N, the task is to check if the array contains only one distinct element or not. If it contains only one distinct element then print âYesâ, otherwise print âNoâ. Examples: Input: arr[] = {3, 3, 4, 3, 3} Output: No Explanation: There are 2 distinct elements present in the
8 min read
Check if two unsorted arrays (with duplicates allowed) have same elements
Given two unsorted arrays, check whether both arrays have the same set of elements or not. Examples: Input : A = {2, 5, 6, 8, 10, 2, 2} B = {2, 5, 5, 6, 8, 5, 6} Output : No Input : A = {2, 5, 6, 8, 2, 10, 2} B = {2, 5, 6, 8, 2, 10, 2} Output : Yes Input : A = {2, 5, 8, 6, 10, 2, 2} B = {2, 5, 6, 8,
13 min read
Find duplicates in an Array with values 1 to N using counting sort
Given a constant array of N elements which contain elements from 1 to N - 1, with any of these numbers appearing any number of times.Examples: Input: N = 5, arr[] = {1, 3, 4, 2, 2} Output: 2 Explanation: 2 is the number occurring more than once.Input: N = 5, arr[] = {3, 1, 3, 4, 2} Output: 3 Explana
11 min read
Find a Fixed Point in an array with duplicates allowed
Given an array of n duplicates or distinct integers sorted in ascending order, write a function that returns a Fixed Point in the array, if there is any Fixed Point present in the array, else returns -1. Fixed Point in an array is an index i such that arr[i] is equal to i. Note that integers in the
8 min read
Check if all duplicate elements in the Array are adjacent or not
Given an array arr[]. The task is to check whether duplicate elements in arr[] are contiguous or not. Examples: Input: arr[] = {1, 2, 3, 4, 5, 6} Output: Yes Explanation: There is no duplicate element in arr[] so there is no need to check anything and answer is Yes. Input: arr[] = {1, 2, 2, 4} Outpu
4 min read
Counting Arrays with divisibility constraint
Given two integers X and Y, the task is to find the number of different arrays that can be constructed of size largest possible size that follow the conditions below: Every element of the array should not be less than X and should not be greater than Y.Every element should occur at most once in the
9 min read