Open In App

Finding Composite Sum Permutation

Given a permutation A of N integers, the task is to find another permutation B such that for every index i, A[i] + B[i] is a composite number. If no permutation is possible, print -1.

Examples:

Input: A[] = {2, 5, 1, 3, 4}
Output: 4 1 5 3 2
Explanation: A = {2 5 1 3 4} and B = {4 1 5 3 2}

  • For i = 0, A[0] + B[0] = 2 + 4 = 6 which is not a prime number.
  • For i = 1, A[1] + B[1] = 5 + 1 = 6 which is not a prime number.
  • For i = 2, A[2] + B[2] = 1 + 5 = 6 which is not a prime number.
  • For i = 3, A[3] + B[3] = 3 + 3 = 6 which is not a prime number.
  • For i = 4, A[4] + B[4] = 4 + 2 = 6 which is not a prime number.

Input: A[] = {2, 1}
Output: -1
Explanation: There is no such permutation exist so print -1.

Approach: To solve the problem, follow the below idea:

We know that on adding two odd numbers or two even numbers, we always get an even number. So, for every index i, make B[i] = A[i] so that we will have even sum for all indices. Among all the even sums, no sum will be prime except 2 (A[i] = 1 and B[i] = 1). To handle this, we simply swap B[i] = 1 with the largest odd number in B[]. Also, if the size of permutation is less than 3, then it is impossible to construct a valid permutation B.

Step-by-step algorithm:

Below is the implementation of the algorithm:

#include <bits/stdc++.h>
using namespace std;

// Function to find the valid permutation B
vector<int> solve(vector<int>& A, int N)
{
    // vector to store array B
    vector<int> B;
  
    // If the permutation has less than three elements, then
    // it is impossible to construct a valid permutation
    if (N < 3)
        return B;
  
    // Variables to store the index of 1 and largest odd
    // number
    int idx1, idx2;
    for (int i = 0; i < N; i++) {
        B.push_back(A[i]);
        // If B[i] = 1, then store its index in idx1
        if (B[i] == 1) {
            idx1 = i;
        }
        // If B[i] = largest odd number, store its index in
        // idx2
        else if ((N % 2 == 0 && B[i] == N - 1)
                 || (N % 2 == 1 && B[i] == N)) {
            idx2 = i;
        }
    }
    // swap 1 and the largest odd number
    swap(B[idx1], B[idx2]);
    return B;
}

// Driver Code
int main()
{
    // Sample Input
    vector<int> A = { 2, 5, 1, 3, 4 };
    int N = A.size();

    vector<int> B = solve(A, N);
    // If size of B is 0, then print -1
    if (B.size() == 0)
        cout << -1 << "\n";
    else {
        for (int i = 0; i < N; i++)
            cout << B[i] << " ";
        cout << "\n";
    }
    return 0;
}
import java.util.ArrayList;

public class ValidPermutation {
    // Function to find the valid permutation B
    static ArrayList<Integer> solve(ArrayList<Integer> A, int N) {
        // ArrayList to store array B
        ArrayList<Integer> B = new ArrayList<>();
      
        // If the permutation has less than three elements, then
        // it is impossible to construct a valid permutation
        if (N < 3)
            return B;
      
        // Variables to store the index of 1 and largest odd number
        int idx1 = -1, idx2 = -1;
        for (int i = 0; i < N; i++) {
            B.add(A.get(i));
            // If B[i] = 1, then store its index in idx1
            if (B.get(i) == 1) {
                idx1 = i;
            }
            // If B[i] = largest odd number, store its index in idx2
            else if ((N % 2 == 0 && B.get(i) == N - 1)
                     || (N % 2 == 1 && B.get(i) == N)) {
                idx2 = i;
            }
        }
        // swap 1 and the largest odd number
        if (idx1 != -1 && idx2 != -1) {
            int temp = B.get(idx1);
            B.set(idx1, B.get(idx2));
            B.set(idx2, temp);
        }
        return B;
    }

    // Driver Code
    public static void main(String[] args) {
        // Sample Input
        ArrayList<Integer> A = new ArrayList<>();
        A.add(2);
        A.add(5);
        A.add(1);
        A.add(3);
        A.add(4);
        int N = A.size();

        ArrayList<Integer> B = solve(A, N);
        // If size of B is 0, then print -1
        if (B.size() == 0)
            System.out.println(-1);
        else {
            for (int i = 0; i < N; i++)
                System.out.print(B.get(i) + " ");
            System.out.println();
        }
    }
}

// This code is contributed by shivamgupta0987654321
def solve(A, N):
    # If the permutation has less than three elements, then
    # it is impossible to construct a valid permutation
    if N < 3:
        return []

    B = A.copy()
    # Variables to store the index of 1 and largest odd number
    idx1, idx2 = None, None
    for i in range(N):
        # If B[i] = 1, then store its index in idx1
        if B[i] == 1:
            idx1 = i
        # If B[i] = largest odd number, store its index in idx2
        elif (N % 2 == 0 and B[i] == N - 1) or (N % 2 == 1 and B[i] == N):
            idx2 = i

    # swap 1 and the largest odd number
    B[idx1], B[idx2] = B[idx2], B[idx1]
    return B

# Driver Code
if __name__ == "__main__":
    # Sample Input
    A = [2, 5, 1, 3, 4]
    N = len(A)

    B = solve(A, N)
    # If size of B is 0, then print -1
    if len(B) == 0:
        print(-1)
    else:
        print(' '.join(map(str, B)))
// Function to find the valid permutation B
function solve(A) {
    // Vector to store array B
    let B = [];
  
    // If the permutation has less than three elements, then
    // it is impossible to construct a valid permutation
    if (A.length < 3)
        return B;
  
    // Variables to store the index of 1 and largest odd
    // number
    let idx1, idx2;
    for (let i = 0; i < A.length; i++) {
        B.push(A[i]);
        // If B[i] = 1, then store its index in idx1
        if (B[i] == 1) {
            idx1 = i;
        }
        // If B[i] = largest odd number, store its index in
        // idx2
        else if ((A.length % 2 == 0 && B[i] == A.length - 1)
                 || (A.length % 2 == 1 && B[i] == A.length)) {
            idx2 = i;
        }
    }
    // Swap 1 and the largest odd number
    [B[idx1], B[idx2]] = [B[idx2], B[idx1]];
    return B;
}

// Driver Code
// Sample Input
let A = [2, 5, 1, 3, 4];

let B = solve(A);
// If size of B is 0, then print -1
if (B.length === 0)
    console.log(-1);
else {
    console.log("Elements are: " + B.join(" "));
}

Output
2 1 5 3 4 

Time Complexity: O(N), where N is the size of permutation.
Auxiliary Space: O(N).

Article Tags :