Check if elements of an array can be arranged in a Circle with consecutive difference as 1
Last Updated :
01 Sep, 2022
Given an array of numbers. The task is to check if it is possible to arrange all the numbers in a circle so that any two neighboring numbers differ exactly by 1. Print “YES” if it is possible to get such arrangement and “NO” otherwise.
Examples:
Input: arr[] = {1, 2, 3, 2}
Output: YES
The circle formed is:
1
2 2
3
Input: arr[] = {3, 5, 8, 4, 7, 6, 4, 7}
Output: NO
Below is the step by step algorithm to solve this problem:
- First insert all the elements in a multiset.
- Remove the first element of the set and store it in a curr variable.
- Traverse until the size of multiset reduced to 0.
- Remove elements that are 1 greater or 1 smaller than the curr value.
- If there is a value with difference more than 1 then “no circle possible”.
- Check if it’s initial and final values of curr variable are same, print “YES” if it is, otherwise print “NO”.
Below is the implementation of above approach:
CPP
#include <bits/stdc++.h>
using namespace std;
int circlePossible( int arr[], int n)
{
multiset< int > s;
for ( int i = 0; i < n; i++)
s.insert(arr[i]);
int cur = *s.begin();
int start = cur;
s.erase(s.begin());
while (s.size()) {
if (s.find(cur + 1) != s.end())
s.erase(s.find(++cur));
else if (s.find(cur - 1) != s.end())
s.erase(s.find(--cur));
else {
cout << "NO" ;
return 0;
}
}
if ( abs (cur - start) == 1)
cout << "YES" ;
else
cout << "NO" ;
return 0;
}
int main()
{
int arr[] = { 1, 1, 2, 2, 2, 3 };
int n = sizeof (arr) / sizeof (arr[0]);
circlePossible(arr, n);
return 0;
}
|
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...