Skip to content
Related Articles

Related Articles

Save Article
Improve Article
Save Article
Like Article

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]

  • Last Updated : 05 Oct, 2021

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:

Attention reader! Don’t stop learning now. Get hold of all the important mathematical concepts for competitive programming with the Essential Maths for CP Course at a student-friendly price. To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

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++




// C++ program for the above approach
#include <bits/stdc++.h>
using namespace std;
 
// Function to check if it is possible
// to generate all numbers in range
// [0, N-1] using the sum of elements
// in the multiset A and B mod N
bool isPossible(multiset<int> A,
                multiset<int> B,
                set<int> C, int N)
{
    // If no more pair of elements
    // can be selected
    if (A.size() == 0 || B.size() == 0) {
 
        // If the number of elements
        // in C = N, then return true
        if (C.size() == N) {
            return true;
        }
 
        // Otherwise return false
        else {
            return false;
        }
    }
 
    // Stores the value of final answer
    bool ans = false;
 
    // Iterate through all the pairs in
    // the given multiset A and B
    for (auto x : A) {
        for (auto y : B) {
 
            // Stores the set A without x
            multiset<int> _A = A;
            _A.erase(_A.find(x));
 
            // Stores the set B without y
            multiset<int> _B = B;
            _B.erase(_B.find(y));
 
            // Stores the set C with (x+y)%N
            set<int> _C = C;
            _C.insert((x + y) % N);
 
            // Recursive call
            ans = (ans
                   || isPossible(
                          _A, _B, _C, N));
        }
    }
 
    // Return Answer
    return ans;
}
 
// Function to check if it is possible
// to rearrange array elements such that
// (arr[i] + i*K) % N = i
void rearrangeArray(
    int arr[], int N, int K)
{
    // Stores the values of arr[] modulo N
    multiset<int> A;
    for (int i = 0; i < N; i++) {
        A.insert(arr[i] % N);
    }
 
    // Stores all the values of
    // i*K modulo N
    multiset<int> B;
    for (int i = 0; i < N; i++) {
        B.insert((i * K) % N);
    }
 
    set<int> C;
 
    // Print Answer
    if (isPossible(A, B, C, N)) {
        cout << "YES";
    }
    else {
        cout << "NO";
    }
}
 
// Driver Code
int main()
{
    int arr[] = { 1, 2, 0 };
    int K = 5;
    int N = sizeof(arr) / sizeof(arr[0]);
 
    rearrangeArray(arr, N, K);
 
    return 0;
}

Python3




# Python3 program for the above approach
 
# Function to check if it is possible
# to generate all numbers in range
# [0, N-1] using the sum of elements
#+ in the multiset A and B mod N
def isPossible(A, B, C, N):
   
     # If no more pair of elements
    # can be selected
    if(len(A) == 0 or len(B) == 0):
       
         # If the number of elements
        # in C = N, then return true
        if(len(C) == N):
            return True
           
        # Otherwise return false
        else:
            return False
           
    # Stores the value of final answer
    ans = False
    for x in A:
       
        # Iterate through all the pairs in
        # the given multiset A and B
        for y in B:
           
           # Stores the set A without x
            _A = A
            _A.remove(x)
             
            # Stores the set A without y
            _B = B
            _B.remove(y)
             
             # Stores the set A without x+y%N
            _C = C
            _C.add((x+y) % N)
             
            # Recursive call
            ans = (ans or isPossible(_A, _B, _C, N))
             
    return ans
 
# Function to check if it is possible
# to rearrange array elements such that
# (arr[i] + i*K) % N = i
def rearrangeArray(arr, N, K):
   
   # Stores the values of arr[] modulo N
    A = []
    for i in range(N):
        A.append(arr[i] % N)
    A.sort()
     
     # Stores all the values of
    # i*K modulo N
    B = []
    for i in range(N):
        B.append((i*K) % N)
    B.sort()
    C = set()
     
    # Print Answer
    if isPossible(A, B, C, N):
        print("YES")
    else:
        print("NO")
 
# Driver code
arr = [1, 2, 0]
K = 5
N = len(arr)
rearrangeArray(arr, N, K)
 
# This code is contributed by parthmanchanda81
Output: 
YES

 

Time Complexity: O(N*2N)
Auxiliary Space: O(1)




My Personal Notes arrow_drop_up
Recommended Articles
Page :