Number of subsequences in a given binary string divisible by 2
Last Updated :
10 Mar, 2022
Given binary string str of length N, the task is to find the count of subsequences of str which are divisible by 2. Leading zeros in a sub-sequence are allowed.
Examples:
Input: str = “101”
Output: 2
“0” and “10” are the only subsequences
which are divisible by 2.
Input: str = “10010”
Output: 22
Naive approach: A naive approach will be to generate all possible sub-sequences and check if they are divisible by 2. The time complexity for this will be O(2N * N).
Efficient approach: It can be observed that any binary number is divisible by 2 only if it ends with a 0. Now, the task is to just count the number of subsequences ending with 0. So, for every index i such that str[i] = ‘0’, find the number of subsequences ending at i. This value is equal to 2i (0-based indexing). Thus, the final answer will be equal to the summation of 2i for all i such that str[i] = ‘0’.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
int countSubSeq(string str, int len)
{
int ans = 0;
int mul = 1;
for ( int i = 0; i < len; i++) {
if (str[i] == '0' )
ans += mul;
mul *= 2;
}
return ans;
}
int main()
{
string str = "10010" ;
int len = str.length();
cout << countSubSeq(str, len);
return 0;
}
|
Java
class GFG
{
static int countSubSeq(String str, int len)
{
int ans = 0 ;
int mul = 1 ;
for ( int i = 0 ; i < len; i++)
{
if (str.charAt(i) == '0' )
ans += mul;
mul *= 2 ;
}
return ans;
}
public static void main(String[] args)
{
String str = "10010" ;
int len = str.length();
System.out.print(countSubSeq(str, len));
}
}
|
Python3
def countSubSeq(strr, lenn):
ans = 0
mul = 1
for i in range (lenn):
if (strr[i] = = '0' ):
ans + = mul
mul * = 2
return ans
strr = "10010"
lenn = len (strr)
print (countSubSeq(strr, lenn))
|
C#
using System;
class GFG
{
static int countSubSeq( string str, int len)
{
int ans = 0;
int mul = 1;
for ( int i = 0; i < len; i++)
{
if (str[i] == '0' )
ans += mul;
mul *= 2;
}
return ans;
}
static public void Main ()
{
string str = "10010" ;
int len = str.Length;
Console.WriteLine(countSubSeq(str, len));
}
}
|
Javascript
<script>
function countSubSeq(str, len)
{
var ans = 0;
var mul = 1;
for ( var i = 0; i < len; i++) {
if (str[i] == '0' )
ans += mul;
mul *= 2;
}
return ans;
}
var str = "10010" ;
var len = str.length;
document.write( countSubSeq(str, len));
</script>
|
Output:
22
Time Complexity: O(len), where len is the size of the given string
Auxiliary Space: O(1)
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...