Generate all binary strings from given pattern - GeeksforGeeks

22 Apr, 2022
Given a string containing of ‘0’, ‘1’ and ‘?’ wildcard characters, generate all binary strings that can be formed by replacing each wildcard character by ‘0’ or ‘1’. Example :  
Input str = "1??0?101"
Output: 
        10000101
        10001101
        10100101
        10101101
        11000101
        11001101
        11100101
        11101101
 
Method 1 (Using Recursion) We pass index of next character to the recursive function. If the current character is a wildcard character ‘?’, we replace it with ‘0’ or ‘1’ and recurse for remaining characters. We print the string if we reach its end. Below is recursive the implementation.  
C++
Java
Python3
C#
PHP
Javascript
// Recursive C++ program to generate all binary strings// formed by replacing each wildcard character by 0 or 1#include <iostream>using namespace std; // Recursive function to generate all binary strings// formed by replacing each wildcard character by 0 or 1void print(string str, int index){    if (index == str.size())    {        cout << str << endl;        return;    }     if (str[index] == '?')    {        // replace '?' by '0' and recurse        str[index] = '0';        print(str, index + 1);         // replace '?' by '1' and recurse        str[index] = '1';        print(str, index + 1);         // No need to backtrack as string is passed        // by value to the function    }    else        print(str, index + 1);} // Driver code to test above functionint main(){    string str = "1??0?101";     print(str, 0);     return 0;}
// Recursive Java program to generate all// binary strings formed by replacing// each wildcard character by 0 or 1import java.util.*;import java.lang.*;import java.io.*; class binStr{      // Recursive function to generate all binary    // strings formed by replacing each wildcard    // character by 0 or 1    public static void print(char str[], int index)    {        if (index == str.length)        {            System.out.println(str);            return;        }         if (str[index] == '?')        {            // replace '?' by '0' and recurse            str[index] = '0';            print(str, index + 1);                         // replace '?' by '1' and recurse            str[index] = '1';            print(str, index + 1);                         // NOTE: Need to backtrack as string            // is passed by reference to the            // function            str[index] = '?';        }        else            print(str, index + 1);    }     // driver code    public static void main (String[] args)    {        String input = "1??0?101";        char[] str = input.toCharArray();        print(str, 0);    }} // This code is contributed by Chhavi
# Recursive Python program to generate all# binary strings formed by replacing# each wildcard character by 0 or 1 # Recursive function to generate all binary# strings formed by replacing each wildcard# character by 0 or 1def _print(string, index):    if index == len(string):        print(''.join(string))        return     if string[index] == "?":         # replace '?' by '0' and recurse        string[index] = '0'        _print(string, index + 1)         # replace '?' by '1' and recurse        string[index] = '1'        _print(string, index + 1)         # NOTE: Need to backtrack as string        # is passed by reference to the        # function        string[index] = '?'    else:        _print(string, index + 1) # Driver codeif __name__ == "__main__":     string = "1??0?101"    string = list(string)    _print(string, 0)     # This code is contributed by    # sanjeev2552 # Note: function name _print is used because# print is already a predefined function in Python
// Recursive C# program to generate all// binary strings formed by replacing// each wildcard character by 0 or 1using System; class GFG{    // Recursive function to generate    // all binary strings formed by    // replacing each wildcard character    // by 0 or 1    public static void print(char []str,                             int index)    {        if (index == str.Length)        {            Console.WriteLine(str);            return;        }         if (str[index] == '?')        {            // replace '?' by            // '0' and recurse            str[index] = '0';            print(str, index + 1);                         // replace '?' by            // '1' and recurse            str[index] = '1';            print(str, index + 1);                         // NOTE: Need to backtrack            // as string is passed by            // reference to the function            str[index] = '?';        }        else            print(str, index + 1);    }     // Driver Code    public static void Main ()    {        string input = "1??0?101";        char []str = input.ToCharArray();        print(str, 0);    }} // This code is contributed by nitin mittal.
<?php// Recursive PHP program to generate all binary strings// formed by replacing each wildcard character by 0 or 1 // Recursive function to generate all binary strings// formed by replacing each wildcard character by 0 or 1function print1($str, $index){    if ($index == strlen($str))    {        echo $str."\n";        return;    }     if ($str[$index] == '?')    {        // replace '?' by '0' and recurse        $str[$index] = '0';        print1($str, $index + 1);         // replace '?' by '1' and recurse        $str[$index] = '1';        print1($str, $index + 1);         // No need to backtrack as string is passed        // by value to the function    }    else        print1($str, $index + 1);} // Driver code     $str = "1??0?101";     print1($str, 0);      // This code is contributed by chandan_jnu?>
<script>       // Recursive JavaScript program to generate all      // binary strings formed by replacing      // each wildcard character by 0 or 1             // Recursive function to generate      // all binary strings formed by      // replacing each wildcard character      // by 0 or 1      function print(str, index) {        if (index === str.length) {          document.write(str.join("") + "<br>");          return;        }         if (str[index] === "?") {          // replace '?' by          // '0' and recurse          str[index] = "0";          print(str, index + 1);           // replace '?' by          // '1' and recurse          str[index] = "1";          print(str, index + 1);           // NOTE: Need to backtrack          // as string is passed by          // reference to the function          str[index] = "?";        } else print(str, index + 1);      }       // Driver Code       var input = "1??0?101";      var str = input.split("");      print(str, 0);       </script>
10000101
10001101
10100101
10101101
11000101
11001101
11100101
11101101
 
Method 2 (Using Queue) We can also achieve this by using iteration. The idea is to use queue. We find position of first occurrence of wildcard character in the input string and replace it by ‘0’ , then ‘1’ and push both strings into the queue. Then we pop next string from the queue, and repeat the process till queue is empty. If no wildcard characters are left, we simply print the string.Iterative C++ implementation using queue.  
C++
Javascript
// Iterative C++ program to generate all binary// strings formed by replacing each wildcard// character by 0 or 1#include <iostream>#include <queue>using namespace std; // Iterative function to generate all binary strings// formed by replacing each wildcard character by 0// or 1void print(string str){    queue<string> q;    q.push(str);     while (!q.empty())    {        string str = q.front();         // find position of first occurrence of wildcard        size_t index = str.find('?');         // If no matches were found,        // find returns string::npos        if(index != string::npos)        {            // replace '?' by '0' and push string into queue            str[index] = '0';            q.push(str);             // replace '?' by '1' and push string into queue            str[index] = '1';            q.push(str);        }         else            // If no wildcard characters are left,            // print the string.            cout << str << endl;         q.pop();    }} // Driver code to test above functionint main(){    string str = "1??0?101";     print(str);     return 0;}
<script> // Iterative JavaScript program to generate all binary// strings formed by replacing each wildcard// character by 0 or 1 // Iterative function to generate all binary strings// formed by replacing each wildcard character by 0// or 1function Print(Str){     let q = []    q.push(Str)     while (q.length > 0){        let Str = q[0]         // find position of first occurrence of wildcard        let index = Str.indexOf('?')             // If no matches were found,        // find returns -1        if(index != -1)        {                     // replace '?' by '0' and push string into queue            Str = Str.replace(Str[index] , '0')            q.push(Str)             // replace '?' by '1' and push string into queue            Str = Str.replace(Str[index] , '1')            q.push(Str)        }         else        {                     // If no wildcard characters are left,            // print the string.            document.write(Str,"</br>")        }         q.shift()    }} // Driver code to test above functionlet Str = "1??0?101"Print(Str) // This code is contributed by shinjanpatra </script>
10000101
10001101
10100101
10101101
11000101
11001101
11100101
11101101
 
Method 3 (Using str and Recursion)  
Python3
Javascript
#we store processed strings in all (array)#we see if string as "?", if so, replace it with 0 and 1#and send it back to recursive func until base case is reached#which is no wildcard left res = []def genBin(s):    if '?' in s:        s1 = s.replace('?','0',1) #only replace once        s2 = s.replace('?','1',1) #only replace once        genBin(s1)        genBin(s2)    else: res.append(s) # Driver codegenBin("1??0?101")print(res) # This code is contributed by# divay pandey
<script>/* we store processed strings in all (array)we see if string as "?", if so, replace it with 0 and 1and send it back to recursive func until base case is reachedwhich is no wildcard left */  let res = []function genBin(s){  if(s.includes('?')){    let s1 = s.replace(/\?/,'0') //only replace once    let s2 = s.replace(/\?/,'1') //only replace once    genBin(s1)    genBin(s2)  }else{    res.push(s)  }}  // Driver codegenBin("1??0?101")document.write(res)  // This code is contributed by// Santanu Panda</script>
['10000101', '10001101', '10100101', '10101101', '11000101', '11001101', '11100101', '11101101']
 
This article is contributed by Aditya Goel. If you like GeeksforGeeks and would like to contribute, you can also write an article and mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. 
nitin mittal
Chandan_Kumar
sanjeev2552
divaypandey
rdtank
shaantalk
shinjanpatra
Amazon
binary-string
Google
Strings
Amazon
Google
Strings
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Check for Balanced Brackets in an expression (well-formedness) using Stack
Python program to check if a string is palindrome or not
KMP Algorithm for Pattern Searching
Array of Strings in C++ (5 Different Ways to Create)
Different methods to reverse a string in C/C++
Convert string to char array in C++
Longest Palindromic Substring | Set 1
Caesar Cipher in Cryptography
Check whether two strings are anagram of each other
Top 50 String Coding Problems for Interviews