![]() |
VOOZH | about |
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:
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.
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)
['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)