Generate all binary strings from given pattern
Last Updated :
23 Jul, 2025
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 do the same for all remaining characters. We print the string if we reach at its end.
Algorithm:
Step 1: Initialize the string first with some wildcard characters in it.
Step 2: Check if index position is equals to the size of string, If it is return.
Step 3: If wildcard character is present at index location, replace it by 0 or 1 accordingly.
Step 4: Print the output
Below is the implementation of the above approach:
C++
// 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 1
void 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 function
int main()
{
string str = "1??0?101";
print(str, 0);
return 0;
}
Java
// Recursive Java program to generate all
// binary strings formed by replacing
// each wildcard character by 0 or 1
import 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
Python3
# 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 1
def _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 code
if __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
C#
// Recursive C# program to generate all
// binary strings formed by replacing
// each wildcard character by 0 or 1
using 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
<?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 1
function 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
?>
JavaScript
<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>
Output: 10000101
10001101
10100101
10101101
11000101
11001101
11100101
11101101
Time Complexity: O(2N), where N is the length of the given string and there are 2 possibilities.
Auxiliary Space: O(N2), as a copy of the string is created in every recursive call.
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++
// 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 1
void 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 function
int main()
{
string str = "1??0?101";
print(str);
return 0;
}
Java
/*package whatever //do not write package name here */
import java.io.*;
import java.util.*;
class GFG {
// Iterative Java 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 1
static void print(String str)
{
Queue<String> q = new LinkedList<>();
q.add(str);
while (!q.isEmpty())
{
str = q.remove();
// find position of first occurrence of wildcard
int index = str.indexOf('?');
// If no matches were found,
// find returns string::npos
if(index != -1)
{
// replace '?' by '0' and add string into queue
str = str.substring(0,index) + '0' + str.substring(index+1);
q.add(str);
// replace '?' by '1' and add string into queue
str = str.substring(0,index) + '1' + str.substring(index+1);
q.add(str);
}
else
// If no wildcard characters are left,
// print the string.
System.out.println(str);
}
}
// Driver Code
public static void main(String args[])
{
String str = "1??0?101";
print(str);
}
}
// This code is contributed by shinjanpatra
Python3
# Iterative Python 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 1
def Print(Str):
q = []
q.append(Str)
while(len(q) > 0):
Str = q[0]
# find position of first occurrence of wildcard
try:
index = Str.index('?')
except ValueError:
index = -1
# If no matches were found,
# find returns -1
if(index != -1):
# replace '?' by '0' and push string into queue
s1=Str.replace('?','0',1)
q.append(s1)
# replace '?' by '1' and push string into queue
s2=Str.replace('?','1',1)
q.append(s2)
else:
# If no wildcard characters are left,
# print the string.
print(Str)
q.pop(0)
# Driver code
Str = "1??0?101"
Print(Str)
# This code is contributed by Pushpesh Raj
C#
// C# program to implement the approach
using System;
using System.Collections.Generic;
public class GFG
{
// Iterative C# 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 1
static void print(string Str)
{
var q = new List<string>();
q.Add(Str);
while (q.Count > 0) {
Str = q[0];
// find position of first occurrence of wildcard
int index = Str.IndexOf('?');
// If no matches were found,
// find returns -1
if (index != -1) {
// replace '?' by '0' and push string into
// queue
Str = Str.Substring(0, index) + '0'
+ Str.Substring(index + 1);
q.Add(Str);
// replace '?' by '1' and push string into
// queue
Str = Str.Substring(0, index) + '1'
+ Str.Substring(index + 1);
q.Add(Str);
}
else {
// If no wildcard characters are left,
// print the string.
Console.WriteLine(Str);
}
q.RemoveAt(0);
}
}
// Driver Code
public static void Main(string[] args)
{
string str = "1??0?101";
// Function call
print(str);
}
}
// This code is contributed by phasing17
JavaScript
<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 1
function 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 function
let Str = "1??0?101"
Print(Str)
// This code is contributed by shinjanpatra
</script>
Output: 10000101
10001101
10100101
10101101
11000101
11001101
11100101
11101101
Time Complexity: O(N*2N), where N is the size of the string.
Auxiliary Space: O(2N)
Method 3 (Using str and Recursion)
C++
// C++ program to implement the approach
#include <bits/stdc++.h>
using namespace std;
/* 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 */
vector<string> res;
void genBin(string s)
{
auto pos = s.find('?');
if (pos != string::npos) {
// copying s to s1
string s1 = s;
// replacing first occurrence of ?
// with 0
s1.replace(pos, 1, "0");
// copying s to s2
string s2 = s;
// replacing first occurrence of ?
// with 1
s2.replace(pos, 1, "1");
genBin(s1);
genBin(s2);
}
else {
res.push_back(s);
}
}
// Driver code
int main()
{
genBin("1??0?101");
for (string x : res) {
cout << x << " ";
}
}
// This code is contributed by phasing17
Java
import java.io.*;
import java.util.*;
class GFG
{
// 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
static ArrayList<String>res = new ArrayList<String>();
static void genBin(String s) {
if (s.indexOf('?') != -1) {
String s1 = s.replaceFirst("\\?", "0"); // only replace once
String s2 = s.replaceFirst("\\?", "1"); // only replace once
genBin(s1);
genBin(s2);
}
else res.add(s);
}
public static void main(String[] args) {
genBin("1??0?101");
System.out.println(res);
}
}
Python3
#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 code
genBin("1??0?101")
print(res)
# This code is contributed by
# divay pandey
C#
// C# code to implement the approach
using System;
using System.Collections.Generic;
class GFG {
// 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
static List<string> res = new List<string>();
static void genBin(string s)
{
int ind = s.IndexOf("?");
if (ind != -1) {
string s1 = s.Remove(ind, 1).Insert(
ind, "0"); // only replace once
string s2 = s.Remove(ind, 1).Insert(
ind, "1"); // only replace once
genBin(s1);
genBin(s2);
}
else
res.Add(s);
}
// Driver code
public static void Main(string[] args)
{
genBin("1??0?101");
foreach(var ele in res) Console.Write(ele + " ");
}
}
// This code is contributed by phasing17
JavaScript
<script>
/* 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 */
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 code
genBin("1??0?101")
document.write(res)
// This code is contributed by
// Santanu Panda
</script>
Output: ['10000101', '10001101', '10100101', '10101101', '11000101', '11001101', '11100101', '11101101']
Time Complexity: O(N*2N), where N is the size of the string.
Auxiliary Space: O(2N)
Similar Reads
Basics & Prerequisites
Data Structures
Array Data StructureIn this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
3 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem