Minimum Suffix Flips - Problem

You have a binary transformation game! You're given a target binary string that you need to match, but you start with a string of all zeros of the same length.

The twist? You can only perform suffix flips - choose any position i and flip all bits from position i to the end of the string. When you flip, all '0's become '1's and all '1's become '0's in that range.

Goal: Find the minimum number of operations to transform your all-zeros string into the target string.

Example: If target = "10", start with "00":
1. Flip from index 1: "00" โ†’ "01"
2. Flip from index 0: "01" โ†’ "10"
Answer: 2 operations

Input & Output

example_1.py โ€” Basic Case
$ Input: target = "10"
โ€บ Output: 2
๐Ÿ’ก Note: Start with "00". First flip from index 1: "00" โ†’ "01". Then flip from index 0: "01" โ†’ "10". Total: 2 operations.
example_2.py โ€” Longer String
$ Input: target = "101"
โ€บ Output: 3
๐Ÿ’ก Note: Start with "000". Flip from index 2: "000" โ†’ "001". Flip from index 1: "001" โ†’ "010". Flip from index 0: "010" โ†’ "101". Total: 3 operations.
example_3.py โ€” All Zeros
$ Input: target = "00"
โ€บ Output: 0
๐Ÿ’ก Note: Start with "00" which already matches target "00". No operations needed.

Constraints

  • 1 โ‰ค target.length โ‰ค 105
  • target[i] is either '0' or '1'
  • The string contains only binary digits

Visualization

Tap to expand
Light Switch TransformationTarget Pattern:101Start State:000Flip 1: Press rightmostAfter Flip 1:001Flip 2: Press leftmostFinal State:101โœ“ Target Achieved in 2 Operations!
Understanding the Visualization
1
Start Position
All switches are OFF (000), target is 101
2
Rightmost Check
Position 2: current=0, target=1, need to flip!
3
Middle Check
Position 1: current=0, target=0, matches!
4
Leftmost Check
Position 0: current=0, target=1, need to flip!
Key Takeaway
๐ŸŽฏ Key Insight: Work backwards! Each position can only be fixed by flipping from that exact position, making the greedy approach optimal.
Asked in
Google 42 Amazon 38 Meta 25 Microsoft 18
28.5K Views
Medium Frequency
~15 min Avg. Time
850 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