Number of Distinct Binary Strings After Applying Operations - Problem

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 from s and flip all its characters, that is, turn all 1's into 0's, and all 0's into 1'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 and 1.
  • A substring is a contiguous part of a string.

Input & Output

Example 1 — Basic Case
$ Input: s = "001", k = 2
Output: 4
💡 Note: We can flip positions [0,1] to get "111", or flip [1,2] to get "010". From "111" we can get "100" by flipping [1,2]. From "010" we can get "100" by flipping [0,1]. All reachable states are: {"001", "111", "010", "100"} giving us 4 distinct strings.
Example 2 — Single Operation
$ Input: s = "10", k = 2
Output: 2
💡 Note: We can apply the flip operation at position 0 to get "01". So we have 2 distinct strings: "10" and "01".
Example 3 — No Operations Possible
$ Input: s = "1", k = 2
Output: 1
💡 Note: String length is 1 but k=2, so no flip operations are possible. Only the original string "1" exists.

Constraints

  • 1 ≤ s.length ≤ 105
  • s consists of only '0' and '1'
  • 1 ≤ k ≤ s.length

Visualization

Tap to expand
Distinct Binary Strings After Operations INPUT Binary String s = "001" 0 idx 0 0 idx 1 1 idx 2 k = 2 Operation: Flip k chars Flip positions [0,1]: "001" --> "111" Length n = 3, k = 2 ALGORITHM STEPS 1 Count Positions Positions: n - k + 1 3 - 2 + 1 = 2 2 Independent Flips Each position: flip or not (2 choices) 3 Calculate Power Result = 2^positions = 2^2 = 4 4 Apply Modulo Return result % (10^9 + 7) All Distinct Strings: "001" (no flip) "111" (flip [0,1]) "010" (flip [1,2]) "100" (flip both) FINAL RESULT 4 Distinct Strings Found "001" "111" "010" "100" Formula Applied: 2^(n-k+1) = 2^2 = 4 OUTPUT 4 OK - Result Verified Key Insight: The number of distinct strings depends only on independent flip positions (n - k + 1). Each position can independently be flipped or not, giving 2^(n-k+1) total combinations. Time: O(log(n-k+1)) for power calculation | Space: O(1) TutorialsPoint - Number of Distinct Binary Strings After Applying Operations | Optimal Solution
Asked in
Google 15 Microsoft 12
15.2K Views
Medium Frequency
~35 min Avg. Time
487 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen