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:
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.