Permutation of an array that has smaller values from another array
Last Updated :
18 Nov, 2022
Given two arrays A and B of equal size. The task is to print any permutation of array A such that the number of indices i for which A[i] > B[i] is maximized.
Examples:
Input: A = [12, 24, 8, 32],
B = [13, 25, 32, 11]
Output: 24 32 8 12
Input: A = [2, 7, 11, 15],
B = [1, 10, 4, 11]
Output: 2 11 7 15
If the smallest element in A beats the smallest element in B, we should pair them. Otherwise, it is useless for our score, as it can't beat any other element of B.
With above strategy we make two vector of pairs, Ap for A and Bp for B with their element and respective index. Then sort both vectors and simulate them. Whenever we found any element in vector Ap such that Ap[i].first > Bp[j].first for some (i, j) we pair them i:e we update our answer array to ans[Bp[j].second] = Ap[i].first. However if Ap[i].first < Bp[j].first for some (i, j) then we store them in vector remain and finally pair them with any one.
Below is the implementation of above approach:
C++
// C++ program to find permutation of an array that
// has smaller values from another array
#include <bits/stdc++.h>
using namespace std;
// Function to print required permutation
void anyPermutation(int A[], int B[], int n)
{
// Storing elements and indexes
vector<pair<int, int> > Ap, Bp;
for (int i = 0; i < n; i++)
Ap.push_back(make_pair(A[i], i));
for (int i = 0; i < n; i++)
Bp.push_back(make_pair(B[i], i));
sort(Ap.begin(), Ap.end());
sort(Bp.begin(), Bp.end());
int i = 0, j = 0, ans[n] = { 0 };
// Filling the answer array
vector<int> remain;
while (i < n && j < n) {
// pair element of A and B
if (Ap[i].first > Bp[j].first) {
ans[Bp[j].second] = Ap[i].first;
i++;
j++;
}
else {
remain.push_back(i);
i++;
}
}
// Fill the remaining elements of answer
j = 0;
for (int i = 0; i < n; ++i)
if (ans[i] == 0) {
ans[i] = Ap[remain[j]].first;
j++;
}
// Output required permutation
for (int i = 0; i < n; ++i)
cout << ans[i] << " ";
}
// Driver program
int main()
{
int A[] = { 12, 24, 8, 32 };
int B[] = { 13, 25, 32, 11 };
int n = sizeof(A) / sizeof(A[0]);
anyPermutation(A, B, n);
return 0;
}
// This code is written by Sanjit_Prasad
Java
// Java program to find permutation of an
// array that has smaller values from
// another array
import java.io.*;
import java.lang.*;
import java.util.*;
class GFG{
// Function to print required permutation
static void anyPermutation(int A[], int B[], int n)
{
// Storing elements and indexes
ArrayList<int[]> Ap = new ArrayList<>();
ArrayList<int[]> Bp = new ArrayList<>();
for(int i = 0; i < n; i++)
Ap.add(new int[] { A[i], i });
for(int i = 0; i < n; i++)
Bp.add(new int[] { B[i], i });
// Sorting the Both Ap and Bp
Collections.sort(Ap, (x, y) -> {
if (x[0] != y[0])
return x[0] - y[0];
return y[1] - y[1];
});
Collections.sort(Bp, (x, y) -> {
if (x[0] != y[0])
return x[0] - y[0];
return y[1] - y[1];
});
int i = 0, j = 0;
int ans[] = new int[n];
// Filling the answer array
ArrayList<Integer> remain = new ArrayList<>();
while (i < n && j < n)
{
// Pair element of A and B
if (Ap.get(i)[0] > Bp.get(j)[0])
{
ans[Bp.get(j)[1]] = Ap.get(i)[0];
i++;
j++;
}
else
{
remain.add(i);
i++;
}
}
// Fill the remaining elements of answer
j = 0;
for(i = 0; i < n; ++i)
if (ans[i] == 0)
{
ans[i] = Ap.get(remain.get(j))[0];
j++;
}
// Output required permutation
for(i = 0; i < n; ++i)
System.out.print(ans[i] + " ");
}
// Driver Code
public static void main(String[] args)
{
int A[] = { 12, 24, 8, 32 };
int B[] = { 13, 25, 32, 11 };
int n = A.length;
anyPermutation(A, B, n);
}
}
// This code is contributed by Kingash
Python3
# Python3 program to find permutation of
# an array that has smaller values from
# another array
# Function to print required permutation
def anyPermutation(A, B, n):
# Storing elements and indexes
Ap, Bp = [], []
for i in range(0, n):
Ap.append([A[i], i])
for i in range(0, n):
Bp.append([B[i], i])
Ap.sort()
Bp.sort()
i, j = 0, 0,
ans = [0] * n
# Filling the answer array
remain = []
while i < n and j < n:
# pair element of A and B
if Ap[i][0] > Bp[j][0]:
ans[Bp[j][1]] = Ap[i][0]
i += 1
j += 1
else:
remain.append(i)
i += 1
# Fill the remaining elements
# of answer
j = 0
for i in range(0, n):
if ans[i] == 0:
ans[i] = Ap[remain[j]][0]
j += 1
# Output required permutation
for i in range(0, n):
print(ans[i], end = " ")
# Driver Code
if __name__ == "__main__":
A = [ 12, 24, 8, 32 ]
B = [ 13, 25, 32, 11 ]
n = len(A)
anyPermutation(A, B, n)
# This code is contributed
# by Rituraj Jain
C#
// Include namespace system
using System;
using System.Collections.Generic;
public class GFG
{
// Function to print required permutation
public static void anyPermutation(int[] A, int[] B, int n)
{
// Storing elements and indexes
List<int[]> Ap = new List<int[]>();
List<int[]> Bp = new List<int[]>();
for (int i = 0; i < n; i++)
{
Ap.Add(new int[]{A[i], i});
}
for (int i = 0; i < n; i++)
{
Bp.Add(new int[]{B[i], i});
}
// Sorting the Both Ap and Bp
Ap.Sort((x,y)=> (x[0] != y[0]) ? x[0] - y[0] : y[1] - y[1]);
Bp.Sort((x,y)=> (x[0] != y[0]) ? x[0] - y[0] : y[1] - y[1]);
var ii = 0;
var j = 0;
int[] ans = new int[n];
// Filling the answer array
var remain = new List<int>();
while (ii < n && j < n)
{
// Pair element of A and B
if (Ap[ii][0] > Bp[j][0])
{
ans[Bp[j][1]] = Ap[ii][0];
ii++;
j++;
}
else
{
remain.Add(ii);
ii++;
}
}
// Fill the remaining elements of answer
j = 0;
for (var i = 0; i < n; ++i)
{
if (ans[i] == 0)
{
ans[i] = Ap[remain[j]][0];
j++;
}
}
// Output required permutation
for (var i = 0; i < n; ++i)
{
Console.Write(ans[i].ToString() + " ");
}
}
// Driver Code
public static void Main(String[] args)
{
int[] A = {12, 24, 8, 32};
int[] B = {13, 25, 32, 11};
var n = A.Length;
GFG.anyPermutation(A, B, n);
}
}
// This code is contributed by aadityaburujwale.
JavaScript
<script>
// JavaScript program to find permutation of
// an array that has smaller values from
// another array
// Function to document.write required permutation
function anyPermutation(A, B, n){
// Storing elements and indexes
let Ap = [], Bp = []
for(let i=0;i<n;i++){
Ap.push([A[i], i])
}
for(let i=0;i<n;i++){
Bp.push([B[i], i])
}
Ap.sort()
Bp.sort()
let i = 0
let j = 0
let ans = new Array(n).fill(0)
// Filling the answer array
let remain = []
while(i < n && j < n){
// pair element of A and B
if(Ap[i][0] > Bp[j][0]){
ans[Bp[j][1]] = Ap[i][0]
i += 1
j += 1
}
else{
remain.push(i)
i += 1
}
}
// Fill the remaining elements
// of answer
j = 0
for(let i=0;i<n;i++){
if(ans[i] == 0){
ans[i] = Ap[remain[j]][0]
j += 1
}
}
// Output required permutation
for(let i=0;i<n;i++){
document.write(ans[i]," ")
}
}
// Driver Code
let A = [ 12, 24, 8, 32 ]
let B = [ 13, 25, 32, 11 ]
let n = A.length
anyPermutation(A, B, n)
// This code is contributed by shinjanpatra
</script>
Time Complexity: O(N*log(N)), where N is the length of array.
Similar Reads
Find whether an array is subset of another array using Map Given two arrays: arr1[0..m-1] and arr2[0..n-1]. Find whether arr2[] is a subset of arr1[] or not. Both the arrays are not in sorted order. It may be assumed that elements in both arrays are distinct.Examples: Input: arr1[] = {11, 1, 13, 21, 3, 7}, arr2[] = {11, 3, 7, 1} Output: arr2[] is a subset o
7 min read
Distribute values from one Array to another Given N and M which is the size of the array a[] and b[] respectively. You have to distribute each element from array b to array a such that the assigned value to each element in a, should be greater than or equal to the current value in a, the task is to return the maximum number of such valid dist
5 min read
Find the missing value from Array B formed by adding some value X to Array A Given two arrays arr1[] and arr2[] of size N and N - 1 respectively. Each value in arr2[] is obtained by adding a hidden value say X to any arr1[i] for N-1 times, which means for any i, arr1[i]+X is not included in arr2[] that is the missing value in arr2[]. The task is to find both the hidden value
10 min read
Print elements of an array according to the order defined by another array | set 2 Given two arrays a1[] and a2[], print elements of a1 in such a way that the relative order among the elements will be the same as those are in a2. That is, elements which come before in the array a2[], print those elements first from the array a1[]. For the elements not present in a2, print them at
7 min read
Check whether an array can be fit into another array rearranging the elements in the array Given two arrays A and B of the same size N. Check whether array A can be fit into array B. An array is said to fit into another array if by arranging the elements of both arrays, there exists a solution such that the ith element of the first array is less than or equal to ith element of the second
6 min read
Rearrange an array so that arr[i] becomes arr[arr[i]] with O(1) extra space Given an array arr[] of size n where every element is in the range from 0 to n-1. Rearrange the given array so that arr[i] becomes arr[arr[i]]. This should be done with O(1) extra spaceExamples: Input: arr[] = [3, 2, 0, 1]Output: arr[] = [1, 0, 3, 2]Explanation: arr[arr[0]] is 1 so arr[0] in output
5 min read
Sort an array according to the order defined by another array Given two arrays arr1[] and arr2[] of size m and n, the task is to sort arr1[] such that the relative order among the elements matches the order in arr2[]. For elements not present in arr2[], append them at the end in sorted order.Example: Input: arr1[] = {2, 1, 2, 5, 7, 1, 9, 3, 6, 8, 8} arr2[] = {
13 min read
Minimum cost required to rearrange a given array to make it equal to another given array Given two arrays A[] and B[] consisting of M and N integers respectively, and an integer C, the task is to find the minimum cost required to make the sequence A exactly the same as B(consists of distinct elements only) by performing the following operations on array A[]: Remove any element from the
12 min read
Closest greater element for every array element from another array Given two arrays a[] and b[], we need to build an array c[] such that every element c[i] of c[] contains a value from a[] which is greater than b[i] and is closest to b[i]. If a[] has no greater element than b[i], then value of c[i] is -1. All arrays are of same size. Examples: Input : a[] = [ 2, 6,
5 min read
Smallest Difference pair of values between two unsorted Arrays Given two arrays of integers, compute the pair of values (one value in each array) with the smallest (non-negative) difference. Return the difference. Examples : Input : A[] = {1, 3, 15, 11, 2} B[] = {23, 127, 235, 19, 8} Output : 3 That is, the pair (11, 8) Input : A[] = {10, 5, 40} B[] = {50, 90,
11 min read