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
DSA Tutorial - Learn Data Structures and Algorithms DSA (Data Structures and Algorithms) is the study of organizing data efficiently using data structures like arrays, stacks, and trees, paired with step-by-step procedures (or algorithms) to solve problems effectively. Data structures manage how data is stored and accessed, while algorithms focus on
7 min read
Quick Sort QuickSort is a sorting algorithm based on the Divide and Conquer that picks an element as a pivot and partitions the given array around the picked pivot by placing the pivot in its correct position in the sorted array. It works on the principle of divide and conquer, breaking down the problem into s
12 min read
Merge Sort - Data Structure and Algorithms Tutorials Merge sort is a popular sorting algorithm known for its efficiency and stability. It follows the divide-and-conquer approach. It works by recursively dividing the input array into two halves, recursively sorting the two halves and finally merging them back together to obtain the sorted array. Merge
14 min read
Bubble Sort Algorithm Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements if they are in the wrong order. This algorithm is not suitable for large data sets as its average and worst-case time complexity are quite high.We sort the array using multiple passes. After the fir
8 min read
Data Structures Tutorial Data structures are the fundamental building blocks of computer programming. They define how data is organized, stored, and manipulated within a program. Understanding data structures is very important for developing efficient and effective algorithms. What is Data Structure?A data structure is a st
2 min read
Breadth First Search or BFS for a Graph Given a undirected graph represented by an adjacency list adj, where each adj[i] represents the list of vertices connected to vertex i. Perform a Breadth First Search (BFS) traversal starting from vertex 0, visiting vertices from left to right according to the adjacency list, and return a list conta
15+ min read
Binary Search Algorithm - Iterative and Recursive Implementation Binary Search Algorithm is a searching algorithm used in a sorted array by repeatedly dividing the search interval in half. The idea of binary search is to use the information that the array is sorted and reduce the time complexity to O(log N). Binary Search AlgorithmConditions to apply Binary Searc
15 min read
Insertion Sort Algorithm Insertion sort is a simple sorting algorithm that works by iteratively inserting each element of an unsorted list into its correct position in a sorted portion of the list. It is like sorting playing cards in your hands. You split the cards into two groups: the sorted cards and the unsorted cards. T
9 min read
Dijkstra's Algorithm to find Shortest Paths from a Source to all Given a weighted undirected graph represented as an edge list and a source vertex src, find the shortest path distances from the source vertex to all other vertices in the graph. The graph contains V vertices, numbered from 0 to V - 1.Note: The given graph does not contain any negative edge. Example
12 min read
Selection Sort Selection Sort is a comparison-based sorting algorithm. It sorts an array by repeatedly selecting the smallest (or largest) element from the unsorted portion and swapping it with the first unsorted element. This process continues until the entire array is sorted.First we find the smallest element an
8 min read