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 these we can generate "000", "100", and "101". Total distinct strings: {"001", "111", "010", "000", "100", "101"} but "100" appears twice, so we have 4 unique 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
Binary String Flip Operations: s="001", k=2"001"Original StringFlip positions 0-1Flip positions 1-2"111""010"From "111":From "010":"000""100""100""101"Distinct Strings: {"001", "111", "010", "000", "100", "101"} → Remove duplicates → Answer: 4
Understanding the Visualization
1
Input
Binary string s="001" and flip length k=2
2
Operations
Apply k-flips at different positions to generate new strings
3
Output
Count total distinct reachable strings
Key Takeaway
🎯 Key Insight: Flip operations form a mathematical group - use linear algebra to count reachable states efficiently
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