Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Missing Permutations in a list in C++
Problem statement
Given a list of permutations of any word. Find the missing permutation from the list of permutations.
Example
If permutation is = { “ABC”, “ACB”, “BAC”, “BCA”} then missing
permutations are {“CBA” and “CAB”}
Algorithm
- Create a set of all given strings
- And one more set of all permutations
- Return difference between two sets
Example
#include <bits/stdc++.h>
using namespace std;
void findMissingPermutation(string givenPermutation[], size_t
permutationSize) {
vector<string> permutations;
string input = givenPermutation[0];
permutations.push_back(input);
while (true) {
string p = permutations.back();
next_permutation(p.begin(), p.end());
if (p == permutations.front())
break;
permutations.push_back(p);
}
vector<string> missing;
set<string> givenPermutations(givenPermutation,
givenPermutation + permutationSize);
set_difference(permutations.begin(), permutations.end(),
givenPermutations.begin(),
givenPermutations.end(),
back_inserter(missing));
cout << "Missing permutations are" << endl;
for (auto i = missing.begin(); i != missing.end(); ++i)
cout << *i << endl;
}
int main() {
string givenPermutation[] = {"ABC", "ACB", "BAC", "BCA"};
size_t permutationSize = sizeof(givenPermutation) / sizeof(*givenPermutation);
findMissingPermutation(givenPermutation, permutationSize);
return 0;
}
When you compile and execute above program. It generates following output −
Output
Missing permutations are CAB CBA
Advertisements