Check if elements of given array can be rearranged such that (arr[i] + i*K) % N = i for all values of i in range [0, N-1]
Given an array arr[] consisting of N positive integers and an integer K, the task is to check if the array elements can be rearranged such that (arr[i] + i*K) % N = i for all values of i in the range [0, N-1].
Examples:
Input: arr[] = {2, 1, 0}, K = 5
Output: Yes
Explanation: The given array can be rearranged to {0, 2, 1}. Hence the values after updation becomes {(0 + 0*5) % 3, (2 + 1*5) % 3, (1 + 2*5) % 3} => {0%3, 7%3, 11%3} => {0, 1, 2} having all elements equal to their indices in the array.
Input: arr[] = {1, 1, 1, 1, 1}, K = 5
Output: No
Naive Approach: The given problem can be solved by generating all the possible permutations of the given array arr[] and check if there exists any such permutation that satisfies the given criteria.
Time Complexity: O(N*N!)
Auxiliary Space: O(N)
Efficient Approach: The above approach can also be optimized with the help of the Set data structure using Recursion. Below are a few observations to solve the given problem:
- The fact that each array element arr[i] is updated as (arr[i] + i*K) % N. So, the value arr[i] % N and i*K % N can be calculated independently.
- If a multiset A contains all the values of arr[i] % N and multiset B contains all the values of i*K % N for all values of i in the range [0, N-1], generate all possible combinations of elements in A and B and store (A[i] + B[i]) % N in a set. If the size of the resulting set is N, it is possible to rearrange the array in the required way.
Using the above observations, the given problem can be solved by the following steps:
- Create a multiset A containing all the values of arr[i] % N for all values of i in the range [0, N-1].
- Similarly, create a multiset B contains all the values of i*K % N for all values of i in the range [0, N-1].
- Create a recursive function to iterate over all pairs of integers in A and B, add their sum modulo N in set C and recursively call for the remaining elements.
- If at any point, the size of the set C = N, return true else return false.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
bool isPossible(multiset< int > A,
multiset< int > B,
set< int > C, int N)
{
if (A.size() == 0 || B.size() == 0) {
if (C.size() == N) {
return true ;
}
else {
return false ;
}
}
bool ans = false ;
for ( auto x : A) {
for ( auto y : B) {
multiset< int > _A = A;
_A.erase(_A.find(x));
multiset< int > _B = B;
_B.erase(_B.find(y));
set< int > _C = C;
_C.insert((x + y) % N);
ans = (ans
|| isPossible(
_A, _B, _C, N));
}
}
return ans;
}
void rearrangeArray(
int arr[], int N, int K)
{
multiset< int > A;
for ( int i = 0; i < N; i++) {
A.insert(arr[i] % N);
}
multiset< int > B;
for ( int i = 0; i < N; i++) {
B.insert((i * K) % N);
}
set< int > C;
if (isPossible(A, B, C, N)) {
cout << "YES" ;
}
else {
cout << "NO" ;
}
}
int main()
{
int arr[] = { 1, 2, 0 };
int K = 5;
int N = sizeof (arr) / sizeof (arr[0]);
rearrangeArray(arr, N, K);
return 0;
}
|
Java
import java.util.ArrayList;
import java.util.HashSet;
class Main {
public static boolean isPossible(ArrayList<Integer> A,
ArrayList<Integer> B, HashSet<Integer> C,
int N) {
if (A.size() == 0 || B.size() == 0 ) {
if (C.size() == N) {
return true ;
}
else {
return false ;
}
}
boolean ans = false ;
for (Integer x : A) {
for (Integer y : B) {
ArrayList<Integer> _A = new ArrayList<Integer>(A);
_A.remove(x);
ArrayList<Integer> _B = new ArrayList<Integer>(B);
_B.remove(y);
HashSet<Integer> _C = new HashSet<Integer>(C);
_C.add((x + y) % N);
ans = (ans
|| isPossible(_A, _B, _C, N));
}
}
return ans;
}
public static void rearrangeArray(
int arr[], int N, int K)
{
ArrayList<Integer> A = new ArrayList<Integer>();
for ( int i = 0 ; i < N; i++) {
A.add(arr[i] % N);
}
ArrayList<Integer> B = new ArrayList<Integer>();
for ( int i = 0 ; i < N; i++) {
B.add((i * K) % N);
}
HashSet<Integer> C = new HashSet<Integer>();
if (isPossible(A, B, C, N)) {
System.out.println( "YES" );
} else {
System.out.println( "NO" );
}
}
public static void main(String[] args) {
int arr[] = { 1 , 2 , 0 };
int K = 5 ;
int N = arr.length;
rearrangeArray(arr, N, K);
}
}
|
Python3
def isPossible(A, B, C, N):
if ( len (A) = = 0 or len (B) = = 0 ):
if ( len (C) = = N):
return True
else :
return False
ans = False
for x in A:
for y in B:
_A = A
_A.remove(x)
_B = B
_B.remove(y)
_C = C
_C.add((x + y) % N)
ans = (ans or isPossible(_A, _B, _C, N))
return ans
def rearrangeArray(arr, N, K):
A = []
for i in range (N):
A.append(arr[i] % N)
A.sort()
B = []
for i in range (N):
B.append((i * K) % N)
B.sort()
C = set ()
if isPossible(A, B, C, N):
print ( "YES" )
else :
print ( "NO" )
arr = [ 1 , 2 , 0 ]
K = 5
N = len (arr)
rearrangeArray(arr, N, K)
|
C#
using System;
using System.Collections.Generic;
class GFG
{
public static bool IsPossible(List< int > A, List< int > B,
HashSet< int > C, int N)
{
if (A.Count == 0 || B.Count == 0)
{
if (C.Count == N) {
return true ;
}
else {
return false ;
}
}
bool ans = false ;
foreach ( int x in A)
{
foreach ( int y in B)
{
List< int > _A = new List< int >(A);
_A.Remove(x);
List< int > _B = new List< int >(B);
_B.Remove(y);
HashSet< int > _C = new HashSet< int >(C);
_C.Add((x + y) % N);
ans = (ans || IsPossible(_A, _B, _C, N));
}
}
return ans;
}
public static void RearrangeArray( int [] arr, int N,
int K)
{
List< int > A = new List< int >();
for ( int i = 0; i < N; i++) {
A.Add(arr[i] % N);
}
List< int > B = new List< int >();
for ( int i = 0; i < N; i++) {
B.Add((i * K) % N);
}
HashSet< int > C = new HashSet< int >();
if (IsPossible(A, B, C, N)) {
Console.WriteLine( "YES" );
}
else {
Console.WriteLine( "NO" );
}
}
public static void Main( string [] args)
{
int [] arr = { 1, 2, 0 };
int K = 5;
int N = arr.Length;
RearrangeArray(arr, N, K);
}
}
|
Javascript
<script>
function isPossible(A, B, C, N){
if (A.length == 0 || B.length == 0){
if (C.size == N)
return true
else
return false
}
let ans = false
for (let x of A){
for (let y of B){
let _A = []
_A = A
_A = _A.filter((a)=>a !== x)
let _B = B
_B = _B.filter((a)=>a !== y)
let _C = C
_C.add((x+y) % N)
ans = ans || isPossible(_A, _B, _C, N)
}
}
return ans
}
function rearrangeArray(arr, N, K){
let A = []
for (let i = 0; i < N; i++)
A.push(arr[i] % N)
A.sort()
let B = []
for (let i = 0; i < N; i++)
B.push((i*K) % N)
B.sort()
let C = new Set()
if (isPossible(A, B, C, N))
document.write( "YES" )
else
document.write( "NO" )
}
let arr = [1, 2, 0]
let K = 5
let N = arr.length
rearrangeArray(arr, N, K)
</script>
|
Time Complexity: O(N*2N)
Auxiliary Space: O(N)
Last Updated :
28 Feb, 2023
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...