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;
}
|
Feeling lost in the world of random DSA topics, wasting time without progress? It's time for a change! Join our DSA course, where we'll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 geeks!
Last Updated :
01 Sep, 2022
Like Article
Save Article