Quantcast
Channel: Coddicted
Viewing all articles
Browse latest Browse all 10

Solved! Leetcode 1529. Minimum Suffix Flips

$
0
0

Description: Minimum Suffix Flips

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.

Example 1

<strong>Input:</strong> target = "10111"
<strong>Output:</strong> 3
<strong>Explanation:</strong> Initially, s = "00000".
Choose index i = 2: "00000" -&gt; "00111"
Choose index i = 0: "00111" -&gt; "11000"
Choose index i = 1: "11000" -&gt; "10111"
We need at least 3 flip operations to form target.

Example 2

<strong>Input:</strong> target = "101"
<strong>Output:</strong> 3
<strong>Explanation:</strong> Initially, s = "000".
Choose index i = 0: "000" -&gt; "111"
Choose index i = 1: "111" -&gt; "100"
Choose index i = 2: "100" -&gt; "101"
We need at least 3 flip operations to form target.

Example 3

<strong>Input:</strong> target = "00000"
<strong>Output:</strong> 0
<strong>Explanation:</strong> We do not need any operations since the initial s already equals target.

Constraints

  • n == target.length
  • 1 <= n <= 105
  • target[i] is either '0' or '1'.

Solution

class Solution {

    public int minFlips(String target) {
        char prev = '0';
        int count = 0;
        for(int i=0;i&lt;target.length();i++){
            char c = target.charAt(i);
            //check if the previous character is same as the current character
            //if not, increment operations count and update prev character
            if(c != prev){
                count++;
                prev = c;
            }
        }

        return count;
    }
}

Time Complexity

O(n), where n is the number of characters in a string

Space Complexity

O(1)

Rate this post


Viewing all articles
Browse latest Browse all 10

Trending Articles