Minimum Suffix Flips - Problem

You are given a 0-indexed binary string target of length n. You have another binary string s of length n that is initially set to all zeros.

You want to make s equal to target.

In one operation, you can pick an index i where 0 <= i < n and flip all bits in the inclusive range [i, n - 1]. Flip means changing '0' to '1' and '1' to '0'.

Return the minimum number of operations needed to make s equal to target.

Input & Output

Example 1 — Basic Case
$ Input: target = "10111"
Output: 3
💡 Note: Start with "00000". Flip at index 0 → "11111". Flip at index 1 → "10000". Flip at index 4 → "10001". Continue until we get "10111" with 3 total operations.
Example 2 — All Zeros
$ Input: target = "000"
Output: 0
💡 Note: Target is already "000" and our string starts as "000", so no operations needed.
Example 3 — All Ones
$ Input: target = "111"
Output: 1
💡 Note: Start with "000". One flip at index 0 gives us "111", which matches the target.

Constraints

  • 1 ≤ target.length ≤ 105
  • target[i] is either '0' or '1'

Visualization

Tap to expand
Minimum Suffix Flips - Greedy Approach INPUT Target String: 1 i=0 0 i=1 1 i=2 1 i=3 1 i=4 Initial String s: 0 0 0 0 0 Operation: Flip all bits from index i to end (n-1) Example: flip from i=1 00000 --> 01111 [1,4] all flipped ALGORITHM STEPS 1 Initialize ops=0, current='0' 2 Scan left to right Compare target[i] vs current 3 If mismatch found Flip: ops++, toggle current 4 Return ops count Total flips needed Trace: i t[i] cur ops 0 1 0->1 1 1 0 1->0 2 2 1 0->1 3 3,4 1,1 1 3 FINAL RESULT After 3 operations: Op 1: Flip from i=0 1 1 1 1 1 Op 2: Flip from i=1 1 0 0 0 0 Op 3: Flip from i=2 1 0 1 1 1 OUTPUT 3 OK Key Insight: Count transitions in target string! Each time target[i] differs from current state, we must flip. The minimum operations = number of bit changes when scanning left to right. Time: O(n), Space: O(1). TutorialsPoint - Minimum Suffix Flips | Greedy - One Pass Left to Right
Asked in
Google 15 Facebook 12 Amazon 8
28.5K Views
Medium Frequency
~15 min Avg. Time
892 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