2450. Number of Distinct Binary Strings After Applying Operations π
Description
You are given a binary string s
and a positive integer k
.
You can apply the following operation on the string any number of times:
- Choose any substring of size
k
froms
and flip all its characters, that is, turn all1
's into0
's, and all0
's into1
's.
Return the number of distinct strings you can obtain. Since the answer may be too large, return it modulo 109 + 7
.
Note that:
- A binary string is a string that consists only of the characters
0
and1
. - A substring is a contiguous part of a string.
Example 1:
Input: s = "1001", k = 3 Output: 4 Explanation: We can obtain the following strings: - Applying no operation on the string gives s = "1001". - Applying one operation on the substring starting at index 0 gives s = "0111". - Applying one operation on the substring starting at index 1 gives s = "1110". - Applying one operation on both the substrings starting at indices 0 and 1 gives s = "0000". It can be shown that we cannot obtain any other string, so the answer is 4.
Example 2:
Input: s = "10110", k = 5 Output: 2 Explanation: We can obtain the following strings: - Applying no operation on the string gives s = "10110". - Applying one operation on the whole string gives s = "01001". It can be shown that we cannot obtain any other string, so the answer is 2.
Constraints:
1 <= k <= s.length <= 105
s[i]
is either0
or1
.
Solutions
Solution 1: Mathematics
Assume the length of the string $s$ is $n$. Then there are $n - k + 1$ substrings of length $k$, and each substring can be flipped, so there are $2^{n - k + 1}$ ways to flip.
The time complexity is $O(n)$, and the space complexity is $O(1)$. Here, $n$ is the length of the string $s$.
1 2 3 |
|
1 2 3 4 5 6 7 8 9 10 11 |
|
1 2 3 4 5 6 7 8 9 10 11 12 |
|
1 2 3 4 5 6 7 8 |
|