Watson asks Does Permutation Exist PERMEXIS

Ashish Patel
Codebrace
Published in
2 min readOct 24, 2016

PROBLEM :- PERMEXIS SUBMIT IN PRACTICE :- SUBMIT

DIFFICULTY :-EASY

PREREQUISITE :-Any Sorting Algorithm Having good time complexity about O(n Log n)

PROBLEM :- You are given with an array, You have to find out that whether on rearranging the array you can come up to the array such that the difference of adjacent elements of array should not exceed by 1. If it is possible to rearrange the array in above manner then print out “YES” , else Print out “NO”.

For More about the Problem and constraints , read the complete Problem HERE.

EXPLANATION:- Just simply apply any sorting technique you know and iterate through the array and check the adjacent elements difference if it does not exceed 1 it’s OK Print “YES” ,else Print “NO”.

EXAMPLES :
Test Case 1:
3 2 2 3
On Applying sorting we get 2 2 3 3 So, no two adjacent elements differ by more than unity so output YES.

Test Case 2:
1 5
On Applying sorting we get 1 5 So, two adjacent elements differ by more than unity so output NO.

CODE IN C++:

#include<iostream>
#include<stdlib.h>
#include<algorithm> // this header is used for in-built sort function of c++.
using namespace std;
typedef long long int ll;
int main()
{
int t,flag;
ll n,*arr,i;
cin>>t;
while(t--)
{
cin>>n;
arr=(ll *)malloc(sizeof(ll)*n);
for(i=0;i<n;i++)
{
cin>>arr[i];
}
sort(arr,arr+n); // it takes 2 iterators and performs sorting in between these start and end iterator(nothing but a pointer).It performs sorting in O(nLogn).
flag=0;
for(i=1;i<n;i++)
{
if(arr[i]-arr[i-1]>1) // checking that whether it exceeded 1 or not
{
flag=1;
break;
}
}
if(flag==0)
{
cout<<"YES\n";
}
else
{
cout<<"NO\n";
}
}
}

#happy_coding #codebrace

If you find something wrong or have any question about the solution then comment down below, you can also contact us using contact form

--

--

Ashish Patel
Codebrace

Big Data Engineer at Skyscanner , loves Competitive programming, Big Data.