LeetCode 1888. Minimum Number of Flips to Make the Binary String Alternating Solution in Java, C++, Python & More | Explanation + Code

CoderIndeed
0
1888. Minimum Number of Flips to Make the Binary String Alternating

Description

You are given a binary string s. You are allowed to perform two types of operations on the string in any sequence:

  • Type-1: Remove the character at the start of the string s and append it to the end of the string.
  • Type-2: Pick any character in s and flip its value, i.e., if its value is '0' it becomes '1' and vice-versa.

Return the minimum number of type-2 operations you need to perform such that s becomes alternating.

The string is called alternating if no two adjacent characters are equal.

  • For example, the strings "010" and "1010" are alternating, while the string "0100" is not.

 

Example 1:

Input: s = "111000"
Output: 2
Explanation: Use the first operation two times to make s = "100011".
Then, use the second operation on the third and sixth elements to make s = "101010".

Example 2:

Input: s = "010"
Output: 0
Explanation: The string is already alternating.

Example 3:

Input: s = "1110"
Output: 1
Explanation: Use the second operation on the second element to make s = "1010".

 

Constraints:

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

Solutions

Solution 1: Sliding Window

We notice that operation 1 effectively turns the string into a cycle, and operation 2 makes a substring of length n within the cycle into an alternating binary string.

Therefore, we only need to enumerate each substring of length n, calculate the cost to make it an alternating binary string, and take the minimum.

We can pre-calculate the number of differences between string s and the two types of alternating binary strings, denoted as cnt. The cost to make s into the first type of alternating binary string is cnt, and the cost to make s into the second type is n - cnt. We initialize ans = min(cnt, n - cnt).

Next, we enumerate each substring of length n and update the value of cnt. For each position i, we subtract the difference of s[i] from the first type of alternating binary string, and add the difference of s[i] to the second type. We update ans = min(ans, cnt, n - cnt).

Finally, return ans.

The time complexity is O(n), where n is the length of the string. The space complexity is O(1).

PythonJavaC++GoTypeScriptRustJavaScriptC#
class Solution: def minFlips(self, s: str) -> int: n = len(s) target = "01" cnt = sum(c != target[i & 1] for i, c in enumerate(s)) ans = min(cnt, n - cnt) for i in range(n): cnt -= s[i] != target[i & 1] cnt += s[i] != target[(i + n) & 1] ans = min(ans, cnt, n - cnt) return ans(code-box)

Post a Comment

0Comments

Post a Comment (0)

#buttons=(Accept !) #days=(20)

Our website uses cookies to enhance your experience. Check Now
Accept !