Write a program that takes in a binary string that also contains x's and prints out all possible binary strings where each x can be replaced with either a 0 or 1.
The Idea: Iterate through the string: when there is an x, append both 0 and 1 to the string, and branch out on each one of these cases. Otherwise just branch by 1.
Complexity: O(2^n + |S| - n) where n is the number of 'x's, and S is the length of the string.
import queuedefbinary_replacement(str):ifnotstr:return [] q = queue.Queue() q.put(('', -1)) sol = []whilenot q.empty(): cum_str, i = q.get()if i +1>=len(str): sol.append(cum_str)whilenot q.empty(): sol.append(q.get()[0])return sol cur_char = str[i+1]if cur_char =='x'or cur_char =='X': q.put((cum_str +'0', i +1)) q.put((cum_str +'1', i +1))else: q.put((cum_str + cur_char, i +1))print(binary_replacement('xx'))print(binary_replacement('1x0X'))print(binary_replacement('1010'))
Recursive Approach
defbinary_replacement(bx): sol = []defdfs(i,cur):iflen(cur)==len(bx): sol.append(cur)returnelse:if bx[i].lower()!='x':dfs(i+1, cur+bx[i])else:dfs(i+1, cur+'1')dfs(i+1, cur+'0')dfs(0, '')return sol