Count permutations possible by replacing ‘?’ characters in a Binary String
Given a string S consisting of characters 0, 1, and ‘?’, the task is to count all possible combinations of the binary string formed by replacing ‘?’ by 0 or 1.
Examples:
Input: S = “0100?110”
Output: 2
Explanation: Replacing each ‘?’s with ‘1’ and ‘0’, the count of such strings formed will be equal to “01001110” and “01000110”. Therefore, the total count of such strings formed is 2.
Input: S = “00?0?111”
Output: 4
Approach: The given problem can be solved based on the following observations:
- Since each ‘?’ can be replaced by ‘0’ or ‘1’, two possible choices exist for every ‘?’ character.
- Now, the task reduces to finding the count of ‘?’s, say count.
- Therefore, the total number of different strings that can be formed is 2count.
Follow the steps below to solve the problem:
Below is the implementation of the above approach:
C++14
#include <bits/stdc++.h>
using namespace std;
void countPermutations(string s){
int count = 0;
for ( char i:s){
if (i == '?' )
count += 1;
}
cout<< pow (2,count);
}
int main()
{
string s = "0100?110" ;
countPermutations(s);
return 0;
}
|
Java
class GFG{
static void countPermutations(String s)
{
int count = 0 ;
for ( char i : s.toCharArray())
{
if (i == '?' )
count += 1 ;
}
System.out.print(( int )Math.pow( 2 ,count));
}
public static void main(String[] args)
{
String s = "0100?110" ;
countPermutations(s);
}
}
|
Python3
def countPermutations(s):
count = 0
for i in s:
if i = = '?' :
count + = 1
print ( 2 * * count)
s = "0100?110"
countPermutations(s)
|
C#
using System;
public class GFG
{
static void countPermutations( string s)
{
int count = 0;
foreach ( char i in s)
{
if (i == '?' )
count += 1;
}
Console.WriteLine(Math.Pow(2,count));
}
public static void Main(String[] args)
{
string s = "0100?110" ;
countPermutations(s);
}
}
|
Javascript
<script>
function countPermutations(s){
var count = 0;
for ( var i =0; i< s.length; i++)
{
if (s[i] == '?' )
count += 1;
}
document.write( Math.pow(2,count));
}
var s = "0100?110" ;
countPermutations(s);
</script>
|
Time Complexity: O(N)
Auxiliary Space: O(1)
Last Updated :
27 Apr, 2021
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...