# Check if a binary string contains all permutations of length k in C++

C++Server Side ProgrammingProgramming

Suppose we have a binary string, another integer k. We have to check the string is containing all permutations of binary of k bits. Suppose a string is like “11001”, and if the K = 2, then it must have all permutations of k bit numbers. (00, 01, 10, 11), the given string has all permutation. So this is valid string.

by taking the binary string and the value of k, we have to check whether binary sequences are matched or not. The binary sequence is made of size k. So there will be 2k number of different binary permutations. We will store all permutations of k length binary value as string in a list, then compare all elements present in the list as subset of the given string. If we get true for all strings present in the list, then the string is valid, otherwise not.

## Example

Live Demo

#include <iostream>
#include <vector>
#include <cmath>
using namespace std;
vector<string> binaryPermutations(int k){
vector<string> list;
int n = 0;
string bin_str = "";
for(int i = 0; i<k; i++){
bin_str += "0";
}
int limit = pow(2, k);
list.push_back(bin_str);
for(int i=1; i<limit; i++){
int j = 0;
while(j <= k){
if(bin_str[k-1-j] == '0'){
bin_str[k - 1 - j] = '1';
break;
} else {
bin_str[k - 1 - j] = '0';
j++;
}
}
list.push_back(bin_str);
}
return list;
}
bool hasAllPermutation(string str, int k){
vector<string> list = binaryPermutations(k);
for(int i = 0; i<list.size(); i++){
string substr = list[i];
std::size_t found = str.find(substr);
if(found == std::string::npos){
return false;
}
}
return true;
}
int main() {
int k = 2;
string str = "11001";
if(hasAllPermutation(str, k)){
cout << "Has All Permutations";
} else {
cout << "Not All Permutations are found";
}
}

## Output

Has All Permutations