![]() |
VOOZH | about |
Given a binary string s and a positive integer k. In a operation you can repeatedly choose any substring of length k in s and flip all its characters (0s to 1s, 1s to 0s). The task is to return the number of distinct strings that can be obtained, modulo 10^9 + 7. You can perform the flip operation any number of times.
Example:
Input: s = "1001", k = 3
Output: 4
Explanation: The four distinct substrings that can be obtained are:
- "1001" (no operation applied)
- "0111" (applying one operation to the substring starting at index 0)
- "1110" (applying one operation to the substring starting at index 1)
- "0000" (applying one operation to both the substrings starting at indices 0 and 1)
Input: s = "10110", k = 5
Output: 2
Explanation: The two distinct substrings that can be obtained are:
- "10110" (no operation applied)
- "01001" (applying one operation to the whole string)
Approach:
The left n-k+1 bits can change to any combination, but the right k-1 bits have a fixed relationship with the kth bit from the right. Therefore the answer to the problem is pow(2, n-k+1).
Below are detailed approach:
We use the following to denote the string, where the 1st from the right is denoted as 1, 2nd as 2, so on and so forth.
n, n-1, .... k+1, k, k-1, k-2, ...., 3, 2, 1
We can easily set the bit n to k with any possible ways, therefore we have 2^(n-k+1) ways.
But, from the k-1 bit on, whatever the original k-1 bit is 0 or 1, the k-1 bit will tightly couple up with the k bit (as both of them participate in the [2k-2, ... k, k-1] group change. If the k bit flip, k-1 bit will flip along. They either change together or do-not-change together.
Likewise, when k-2 bit participates in the change of the [2k-3, ... k, k-1, k-2] group, the k-2 bit tightly couples up with the k and k-1 bits. These three bits either change together or do-not-change together.
This relationship goes on to the end of the string.
Steps-by-step approach:
Below are the implementation of the above approach:
Number of distinct substrings: 4
Time Complexity: O(log n), where n is the length of the input string s
Auxiliary Space: O(1)