1758. Minimum Changes To Make Alternating Binary String
You are given a binary string s
. You are allowed to perform two types of operations on the string:
Return the minimum number of operations required to make s
alternating.
An alternating binary string is a string in which no two adjacent characters are the same. For example, “010” and “101” are alternating binary strings, while “00” and “111” are not.
Example:
Input: s = "0100"
Output: 1
Explanation: We can remove the last character to get "010" which is an alternating string.
s
?
To solve this problem, we need to convert the given string s
into an alternating binary string with the minimum number of changes. An alternating binary string can start with either ‘0’ or ‘1’. We’ll consider both possibilities and count the number of changes needed for each.
We’ll compare s
against both patterns and count the necessary changes for each scenario. The minimum of these two counts will be our answer.
s
and for each character, compare it with the expected character in both patterns.def min_operations_to_alternate(s: str) -> int:
n = len(s)
# Two patterns to compare against
pattern1, pattern2 = '0', '1'
count1 = count2 = 0
for i in range(n):
# For pattern starting with '0' (010101...)
if s[i] != pattern1:
count1 += 1
# For pattern starting with '1' (101010...)
if s[i] != pattern2:
count2 += 1
# Alternate the patterns
pattern1, pattern2 = pattern2, pattern1
return min(count1, count2)
# Example usage
s = "0100"
print(min_operations_to_alternate(s)) # Output should be 1
s
, as we are traversing the string once.This approach ensures we efficiently determine the minimum changes needed to convert the binary string into an alternating binary string.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?