Number of Distinct Binary Strings After Applying Operations Problem
#2450
Try it yourself first
Five languages, sample and hidden tests, right in the browser.
Practice it as an interview
Talk through your solution with an AI interviewer while you code.
Description
LeetCode Problem 2450.
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
kfromsand 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 10^9 + 7.
Note that:
- A binary string is a string that consists only of the characters
0and1. - 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 <= 10^5s[i]is either0or1.
Solution
Approach: Mathematics
A string of length n has n - k + 1 windows of length k, and each window can independently be flipped or not. All these choices give different results, so there are 2^(n - k + 1) distinct strings. Return it modulo 10^9 + 7.
Complexity: O(n) time (or O(log n) with fast exponentiation) and O(1) space.
class Solution:
def countDistinctStrings(self, s: str, k: int) -> int:
return pow(2, len(s) - k + 1) % (10**9 + 7)