Given a 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 is allowed.
Input: str = “101”
“0” and “10” are the only subsequences
which are divisible by 2.
Input: str = “10010”
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:
GeeksforGeeks has prepared a complete interview preparation course with premium videos, theory, practice problems, TA support and many more features. Please refer Placement 100 for details
- Number of subsequences in a string divisible by n
- Minimum number of palindromic subsequences to be removed to empty a binary string
- Number of sub-strings in a given binary string divisible by 2
- Number of sub-sequences of non-zero length of a binary string divisible by 3
- Maximum splits in binary string such that each substring is divisible by given odd number
- Given a number as a string, find the number of contiguous subsequences which recursively add up to 9 | Set 2
- Given a number as a string, find the number of contiguous subsequences which recursively add up to 9
- Largest sub-string of a binary string divisible by 2
- Number of subsequences as "ab" in a string repeated K times
- Number of ways to partition a string into two balanced subsequences
- Minimum number of subsequences required to convert one string to another
- Longest sub-sequence of a binary string divisible by 3
- Decimal representation of given binary string is divisible by 5 or not
- Minimum number of subsequences required to convert one string to another using Greedy Algorithm
- Minimum swaps required to make a binary string divisible by 2^k
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.