C++ Program to find permutation from merged permutations


Suppose we have an array A with 2n number of elements. We know a permutation of first n natural numbers is a set of numbers where 1 to n are stored and they are ordered in an arbitrary order. in the array A, there are two permutations of size n are merged together. When they are merged the relative order of the elements remains unchanged. So if a permutation p is like p = [3,1,2] some possible results are: [3,1,2,3,1,2], [3,3,1,1,2,2], [3,1,3,1,2,2]. The following sequences are not possible results of a merging: [1,3,2,1,2,3], [3,1,2,3,2,1], [3,3,1,2,2,1] as their relative orders are different. From A, we have to restore the permutation, and it will be unique.

Problem Category

The given problem is an example of a divide-and-conquer problem that we can solve using Dynamic programming. Dynamic programming is a type of divide-and-conquer technique where a particular problem is divided into subproblems and then solved. There is a difference between the normal divide-and-conquer technique and dynamic programming, that is the latter solves the overlapping subproblems and uses that result whenever it is needed again. To store the result of these overlapping subproblems, the dynamic programming technique uses a table, and this process is called 'memoization'. The data from the table is examined each time a subproblem has to be solved. Typically, dynamic programming techniques are used for optimization problems where an optimal value of a solution has to be found. Examples of this programming technique include Fibonacci series problems, Bellman-Ford single-source shortest path problem, matrix chain multiplication problem, longest common subsequence problem, etc.

https://www.tutorialspoint.com/data_structures_algorithms/dynamic_programming.htm

Steps

To solve this, we will follow these steps −

n := size of A
Define an array b of size: 51 fill with 0
for initialize i := 0, when i < 2 * n, update (increase i by 1), do:
   a := A[i]
   if b[a] is same as 0, then:
      print a
   b[a] := 1

Example

Let us see the following implementation to get better understanding −

#include <bits/stdc++.h>
using namespace std;
void solve(vector<int> A){
   int n = A.size() / 2;
   bool b[51] = { 0 };
   for (int i = 0; i < 2 * n; i++){
      int a = A[i];
      if (b[a] == 0)
         cout << a << ", ";
      b[a] = 1;
   }
}
int main(){
   vector<int> A = { 1, 3, 1, 4, 3, 4, 2, 2 };
   solve(A);
}

Input

{ 1, 3, 1, 4, 3, 4, 2, 2 }

Output

1, 3, 4, 2,

Updated on: 08-Apr-2022

150 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements