Check if a binary string contains all permutations of length k
Last Updated :
20 Feb, 2023
Given a binary string and k, to check whether it's contains all permutations of length k or not.
Examples:
Input : Binary string 11001
k : 2
Output : Yes
11001 contains all possibilities of
binary sequences with k = 2, 00, 01,
10, 11
Input : Binary string: 1001
k : 2
Output: No
1001 does not contain all possibilities of
binary sequences with k = 2. Here 11
sequence is missing
Method 1:
Explanation:
In this example one binary sequence of length k is not found it is 0110.
So all binary sequences with k=4 will be 24=16. they are following
0000, 0001, 0010, 0011, 0100, 0101, 0110, 0111,
1000, 1001, 1010, 1011, 1100, 1101, 1110, 1111
All should be sub string of given binary string then print Yes otherwise No
Algorithm:
Taking binary string and the size k. In binary string we check binary sequences are matched or not. Binary sequence is made of size k, as we know that in binary using 0 and 1 digit so to generate total binary subsets is 2k element. The main idea behind it, to store all binary value in list as string and then compare list all item to given binary string as subset. If all are occur inside the binary string then print "Yes" otherwise print "No".
Implementation:
C++
#include <bits/stdc++.h>
using namespace std;
// Generate all binary subsets of given length k.
vector<string> binarySubsets(int k)
{
vector<string> list;
// Loop for 2^k elements
for (int i = 0; i < pow(2, k); i++)
{
// Add all possible binary sequence of given length
// to the list
list.push_back(
bitset<32>(i).to_string().substr(32 - k));
}
return list;
}
// Check if binary string contains all permutations of
// length k.
bool tocheck(const string& s, int k)
{
vector<string> list = binarySubsets(k);
// Check if binary sequences are available in string or
// not
for (const auto& b : list) {
if (s.find(b) == string::npos) {
return false;
}
}
return true;
}
// Driver code
int main()
{
string str = "11001";
int num = 2;
// Function call
if (tocheck(str, num)) {
cout << "Yes" << endl;
}
else {
cout << "No" << endl;
}
return 0;
}
// This code is contributed by phasing17.
Java
// Java program to Check a binary string
// contains all permutations of length k.
import java.util.*;
public class Checkbinary {
// to check all Permutation in given String
public static boolean tocheck(String s, int k)
{
List<String> list = BinarySubsets(k);
// to check binary sequences are available
// in string or not
for (String b : list)
if (s.indexOf(b) == -1)
return false;
return true;
}
// to generate all binary subsets of given length k
public static List<String> BinarySubsets(int k)
{
// Declare the list as String
List<String> list = new ArrayList<>();
// to define the format of binary of
// given length k
String format = "%0" + k + "d";
// returns the string representation of the
// unsigned integer value represented by
// the argument in binary (base 2) using
// Integer.toBinaryString and convert it
// into integer using Integer.valueOf.
// Loop for 2<sup>k</sup> elements
for (int i = 0; i < Math.pow(2, k); i++)
{
// To add in the list all possible
// binary sequence of given length
list.add(String.format(format,
Integer.valueOf(Integer.toBinaryString(i))));
/* To Show all binary sequence of given
length k
System.out.println(String.format(format,
Integer.valueOf(Integer.toBinaryString(i))));*/
}
return list;
}
// drive main
public static void main(String[] args)
{
String str = "11001";
int num = 2;
if (tocheck(str, num))
System.out.println("Yes");
else
System.out.println("No");
}
}
Python3
# Python3 program to Check a binary string
# contains all permutations of length k.
def tocheck(s, k):
list1 = binary_subsets(k)
# to check binary sequences are available
# in string or not
for b in list1:
if s.find(b) == -1:
return False
return True
# to generate all binary subsets of given length k
def binary_subsets(k):
# Declare the list as array
list1 = []
# to define the format of binary of
# given length k
format = '0' * k
# returns the string representation of the
# unsigned integer value represented by
# the argument in binary (base 2)
# Loop for 2^k elements
for i in range(2 ** k):
# To add in the list all possible
# binary sequence of given length
list1.append(format[0:k - len(bin(i)[2:])] + bin(i)[2:])
return list1
# driver code
string = "11001"
num = 2
# function call
if tocheck(string, num):
print("Yes")
else:
print("No")
# This code is contributed by phasing17
C#
// C# code to implement the approach
using System;
using System.Collections.Generic;
class GFG {
// to check all Permutation in given String
public static bool ToCheck(string s, int k)
{
var list = BinarySubsets(k);
// to check binary sequences are available
// in string or not
foreach(string b in list) if (s.IndexOf(b)
== -1) return false;
return true;
}
// to generate all binary subsets of given length k
public static List<string> BinarySubsets(int k)
{
// Declare the list as String
var list = new List<string>();
// to define the format of binary of
// given length k
var format = "{0:D" + k + "}";
// Loop for 2^k elements
for (int i = 0; i < Math.Pow(2, k); i++) {
// To add in the list all possible
// binary sequence of given length
list.Add(string.Format(format,
Convert.ToString(i, 2)));
/* To Show all binary sequence of given
length k
Console.WriteLine(string.Format(format,
Convert.ToString(i, 2)));*/
}
return list;
}
// drive main
public static void Main(string[] args)
{
var str = "11001";
var num = 2;
if (ToCheck(str, num))
Console.WriteLine("Yes");
else
Console.WriteLine("No");
}
}
// This code is contributed by phasing17
JavaScript
// JavaScript program to Check a binary string
// contains all permutations of length k.
function tocheck(s, k) {
let list = binarySubsets(k);
// to check binary sequences are available
// in string or not
for (let b of list) {
if (s.indexOf(b) === -1) {
return false;
}
}
return true;
}
// to generate all binary subsets of given length k
function binarySubsets(k) {
// Declare the list as array
let list = [];
// to define the format of binary of
// given length k
let format = '0'.repeat(k);
// returns the string representation of the
// unsigned integer value represented by
// the argument in binary (base 2) using
// parseInt(n,2) and convert it
// into integer using toString(2).
// Loop for 2^k elements
for (let i = 0; i < Math.pow(2, k); i++) {
// To add in the list all possible
// binary sequence of given length
list.push(i.toString(2).padStart(k, '0'));
}
return list;
}
// driver code
let str = "11001";
let num = 2;
// function call
if (tocheck(str, num)) {
console.log("Yes");
} else {
console.log("No");
}
// This code is contributed by phasing17
Method 2:
Algorithm:
Taking binary string and the size k. In binary string we check binary sequences are matched or not. Binary sequence is made of size k, as we know that in binary using 0 and 1 digit so to generate total binary subsets is 2k element.
The main idea behind it, to store all the substring of size k of the given string to the set i.e. storing the distinct substring of size k. If the size of the set is equal to 2k then print "YES" otherwise print "NO".
Implementation:
C++
// C++ Program to Check If a
// String Contains All Binary
// Codes of Size K
#include <bits/stdc++.h>
using namespace std;
#define int long long
bool hasAllcodes(string s, int k)
{
// Unordered map of type string
unordered_set<string> us;
for (int i = 0; i + k <= s.size(); i++)
{
us.insert(s.substr(i, k));
}
return us.size() == 1 << k;
}
// Driver Code
signed main()
{
string s = "00110110";
int k = 2;
if (hasAllcodes)
{
cout << "YES\n";
}
else
{
cout << "NO\n";
}
}
Java
// Java Program to Check If a
// String Contains All Binary
// Codes of Size K
import java.io.*;
import java.util.*;
class GFG
{
static boolean hasAllcodes(String s, int k)
{
// Unordered map of type string
Set<String> us= new HashSet<String>();
for(int i = 0; i + k <= s.length(); i++)
{
us.add(s.substring(i, i + k));
}
return (us.size() == (1 << k));
}
// Driver code
public static void main (String[] args)
{
String s = "00110110";
int k = 2;
if(hasAllcodes(s, k))
{
System.out.println("YES");
}
else
{
System.out.println("NO");
}
}
}
// This code is contributed by avanitrachhadiya2155
Python3
# Python3 Program to Check If a
# String Contains All Binary
# Codes of Size K
def hasAllcodes(s, k) :
# Unordered map of type string
us = set()
for i in range(len(s) + 1) :
us.add(s[i : k])
return len(us) == 1 << k
# Driver code
s = "00110110"
k = 2
if (hasAllcodes) :
print("YES")
else :
print("NO")
# This code is contributed by divyeshrabadiya07
C#
// C# Program to Check If a
// String Contains All Binary
// Codes of Size K
using System;
using System.Collections.Generic;
class GFG {
static bool hasAllcodes(string s, int k)
{
// Unordered map of type string
HashSet<string> us = new HashSet<string>();
for (int i = 0; i + k <= s.Length; i++)
{
us.Add(s.Substring(i, k));
}
return us.Count == 1 << k;
}
// Driver code
static void Main()
{
string s = "00110110";
int k = 2;
if(hasAllcodes(s, k))
{
Console.WriteLine("YES");
}
else
{
Console.WriteLine("NO");
}
}
}
// This code is contributed by divyesh072019
JavaScript
<script>
// Javascript program to Check If a
// String Contains All Binary
// Codes of Size K
function hasAllcodes(s,k)
{
// Unordered map of type string
let us = new Set();
for(let i = 0; i + k <= s.length; i++)
{
us.add(s.substring(i, i + k));
}
return (us.size == (1 << k));
}
// Driver code
let s = "00110110";
let k = 2;
if (hasAllcodes(s, k))
{
document.write("YES");
}
else
{
document.write("NO");
}
// This code is contributed by ab2127
</script>
Time Complexity: O(n) we iterating over string from index 0 to n-k, so O(n) time complexity
Space Complexity: O(2k) as here, in the above solution we are creating an unordered set which stores the all possible binary substring of size k so space complexity will be 2k
Method : 3 (Two Pointer Based)
In this method, we will take a window of size k and move that window to the end, and mark all possible permutations in the visited array. then check if there is any value that is not marked as visited then return false, otherwise return true.
Implementation:
C++
#include <bits/stdc++.h>
using namespace std;
bool hasAllCodes(string s, int k)
{
int n = s.size();
if (n < k)
return false;
int size = pow(2, k);
vector<bool> visited(size, false);
int i = 0;
int j = 0;
int val = 0;
while (j < k - 1) {
val = 2 * val + (s[j] - '0');
j++;
}
while (j < n) {
val = 2 * val + (s[j] - '0');
visited[val] = true;
if (s[i] == '1')
val -= pow(2, k - 1);
j++;
i++;
}
for (int i = 0; i < size; i++) {
if (!visited[i])
return false;
}
return true;
}
// Driver Code
int main()
{
string s = "00110110";
int k = 2;
if (hasAllCodes(s, k)) {
cout << "YES\n";
}
else {
cout << "NO\n";
}
}
Java
// Java program to implement the approach
import java.util.*;
class GFG {
// Method to check if the string contnains
// all the binary codes of size k
static boolean hasAllCodes(String s, int k)
{
int n = s.length();
if (n < k)
return false;
int size = (int)Math.pow(2, k);
// ArrayList that tracks if a certain code
// has been found
ArrayList<Boolean> visited
= new ArrayList<Boolean>();
for (int i = 0; i < size; i++)
visited.add(false);
int i = 0;
int j = 0;
int val = 0;
while (j < k - 1) {
val = 2 * val + (s.charAt(j) - '0');
j++;
}
while (j < n) {
val = 2 * val + (s.charAt(j) - '0');
visited.set(val, true);
if (s.charAt(i) == '1')
val -= (int)Math.pow(2, k - 1);
j++;
i++;
}
// Checking if all the codes have been found
for (i = 0; i < size; i++) {
if (!visited.get(i))
return false;
}
return true;
}
// Driver Code
public static void main(String[] args)
{
String s = "00110110";
int k = 2;
// Function call
if (hasAllCodes(s, k)) {
System.out.print("YES\n");
}
else {
System.out.print("NO\n");
}
}
}
// This code is contributed by phasing17
Python3
# Python3 Program to Check If a String Contains All Binary Codes of Size K
def hasAllcodes(s, k):
n = s.len()
size = pow(2, k)
visited = [True for i in range(size)]
i = 0
j = 0
val = 0
while(j < k-1):
val = (2 * val) + (s[j] - '0')
j += 1
while(j < size):
val = (2 * val) + (s[j] - '0')
visited[val] = True
if(s[i] == '1'):
val = val - pow(2,k-1)
j += 1
i += 1
for i in range(size):
if(visited[i] == False):
return False
return True
# Driver code
s = "00110110"
k = 2
if (hasAllcodes):
print("YES")
else:
print("NO")
# This code is contributed by Ajay Makvana
C#
// C# code for the above approach
using System;
using System.Collections.Generic;
class GFG
{
// Method to check if the string contnains
// all the binary codes of size k
static bool hasAllCodes(string s, int k)
{
int n = s.Length;
if (n < k)
return false;
int size = (int)Math.Pow(2, k);
bool[] visited=new bool[size];
int i = 0;
// ArrayList that tracks if a certain code
// has been found
for(i=0; i<size; i++)
visited[i] = false;
i=0;
int j = 0;
int val = 0;
while (j < k - 1) {
val = 2 * val + ((int)s[j]-'0');
j++;
}
while (j < n) {
int x= ((int)s[j]-'0');
val = 2 * val + x;
visited[val] = true;
if (s[i] == '1')
val -= ((int)Math.Pow(2, k - 1));
j++;
i++;
}
for (i = 0; i < size; i++) {
if (!visited[i])
return false;
}
return true;
}
// Driver Code
static void Main(string[] args)
{
string s = "00110110";
int k = 2;
if (hasAllCodes(s, k)) {
Console.WriteLine("YES");
}
else {
Console.WriteLine("NO");
}
}
}
JavaScript
// JavaScript Program to Check If a String Contains All Binary Codes of Size K
function hasAllcodes(s, k)
{
var n = s.length;
var size = Math.pow(2, k);
var visited = new Array(size).fill(true);
var i = 0;
var j = 0;
var val = 0;
while (j < k-1)
{
val = (2 * val) + (s[j] - '0');
j += 1;
}
while (j < size)
{
val = (2 * val) + (s[j] - '0');
visited[val] = true;
if(s[i] == '1')
val = val - Math.pow(2, k - 1);
j += 1;
i += 1;
}
for (var i = 0; i < size; i++)
{
if(visited[i] == false)
return false;
}
return true;
}
// Driver code
var s = "00110110";
var k = 2;
if (hasAllcodes)
console.log("YES");
else
console.log("NO");
// This code is contributed by phasing17
Time Complexity : O(n)
Space Complexity: O(2k) as here, in the above solution we are creating a visited array of size pow(2,k) so we need that extra space
Similar Reads
Check if all substrings of length K of a Binary String has equal count of 0s and 1s
Given a binary string S of length N and an even integer K, the task is to check if all substrings of length K contains an equal number of 0s and 1s. If found to be true, print âYesâ. Otherwise, print âNoâ. Examples: Input: S = "101010", K = 2Output: YesExplanation:Since all the substrings of length
6 min read
Check if any permutation of N equals any power of K
Given a positive integer N and K where 2 \leq N \leq 10^{18} and 2 \leq K \leq N . The task is to check whether any permutation of digits of N equals any power of K. If possible return "True" otherwise return "False".Examples: Input: N = 96889010407, K = 7 Output: True Explanation: 96889010407 = 713
6 min read
Distinct Numbers obtained by generating all permutations of a Binary String
Given a binary string S, the task is to print all distinct decimal numbers that can be obtained by generating all permutations of the binary string. Examples: Input: S = "110"Output: {3, 5, 6}Explanation: All possible permutations are {"110", "101", "110", "101", "011", "011"}.Equivalent decimal num
8 min read
Generate all permutations of a string that follow given constraints
Given a string, generate all permutations of it that do not contain 'B' after 'A', i.e., the string should not contain "AB" as a substring. Examples: Input : str = "ABC" Output : ACB, BAC, BCA, CBA Out of 6 permutations of "ABC", 4 follow the given constraint and 2 ("ABC" and "CAB") do not follow. I
11 min read
Check if a Sequence is a concatenation of two permutations
Given an array arr containing positive integers, the task is to check if the given array arr is a concatenation of two permutations or not. A sequence of M integers is called a permutation if it contains all integers from 1 to M exactly once. Examples: Input: arr[] = {1, 2, 5, 3, 4, 1, 1} Output: No
8 min read
Minimum length of string having all permutation of given string.
Given a string S where 1\leq length\; of\; S\leq 26 . Assume that all the characters in S are unique. The task is to compute the minimum length of a string which consists of all the permutations of the given string in any order. Note: All permutations must be present as a substring in the resulting
4 min read
Check if a string consists of two K-length non-overlapping substrings as anagrams
Given a string str of length N and an integer K, the task is to check if a string has two non-overlapping substrings of length K as anagrams. Examples: Input: str = "ginfing", K = 3Output: YesExplanation:"gin" and "ing" are the two non overlapping substrings of length 3 which are anagrams.Therefore,
9 min read
Check if given number contains only â01â and â10â as substring in its binary representation
Given a number N, the task is to check if the binary representation of the number N has only "01" and "10" as a substring or not. If found to be true, then print "Yes". Otherwise, print "No".Examples: Input: N = 5 Output: Yes Explanation: (5)10 is (101)2 which contains only "01" and "10" as substrin
6 min read
Count of setbits in bitwise OR of all K length substrings of given Binary String
Given a binary string str of length N, the task is to find the number of setbits in the bitwise OR of all the K length substrings of string str. Examples: Input: N = 4, K = 3, str = "1111"Output: 3Explanation: All 3-sized substrings of S are:"111" and "111". The OR of these strings is "111". Therefo
8 min read
Check if any permutation of string is a K times repeated string
Given a string S and an integer K, the task is to check that if any permutation of the string can be formed by K times repeating any other string.Examples: Input: S = "abba", K = 2 Output: Yes Explanation: Permutations of given string - {"aabb", "abab", "abba", "baab", "baba", "bbaa"} As "abab" is r
13 min read