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
Basics & Prerequisites
Data Structures
Array Data StructureIn this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
3 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem