Given a binary string S of length N, the task is to find the number of sub-sequences of non-zero length which are divisible by 3. Leading zeros in the sub-sequences are allowed.
Input: S = “1001”
“11”, “1001”, “0”, “0” and “00” are
the only subsequences divisible by 3.
Input: S = “1”
Naive approach: Generate all the possible sub-sequences and check if they are divisible by 3. Time complexity for this will be O((2N) * N).
Better approach: Dynamic programming can be used to solve this problem. Let’s look at the states of the DP.
DP[i][r] will store the number of sub-sequences of the substring S[i…N-1] such that they give a remainder of (3 – r) % 3 when divided by 3.
Let’s write the recurrence relation now.
DP[i][r] = DP[i + 1][(r * 2 + s[i]) % 3] + DP[i + 1][r]
The recurrence is derived because of the two choices below:
- Include the current index i in the sub-sequence. Thus, the r will be updated as r = (r * 2 + s[i]) % 3.
- Don’t include current index in the sub-sequence.
Below is the implementation of the above approach:
Time Complexity: O(n)
- Number of subsequences in a given binary string divisible by 2
- 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 palindromic subsequences of length k where k <= 3
- Number of ways to make binary string of length N such that 0s always occur together in groups of size K
- Number of subsequences of maximum length K containing no repeated elements
- Given a number as a string, find the number of contiguous subsequences which recursively add up to 9
- Given a number as a string, find the number of contiguous subsequences which recursively add up to 9 | Set 2
- 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
- Decimal representation of given binary string is divisible by 5 or not
- Longest sub-sequence of a binary string divisible by 3
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. 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.