Statement▼
Given a binary string s
, the following two operations can be performed 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 from the string and flip its value. In other words, if its value is
0 , it becomes1 , and vice versa.
Your task is to return the minimum number of type-s
becomes alternating.
Note: The string is called alternating if no two adjacent characters are equal.
Constraints:
1≤ s.length
≤105 s[i]
is either0 or1 .
Solution
The problem involves transforming a binary string into an alternating pattern with minimum type 2 operations (flipping a character). The solution uses a sliding window pattern to evaluate all cyclic permutations of the string. By maintaining a window of length equal to the string, we compute the number of flips required to match either of the two alternating patterns (“
Now, let’s walk through the steps of the solution.
First, we find the length of the input string
s
and store it in a variable,n
. This helps manage iterations over the string and handle all its cyclic permutations.We store the target pattern in a variable,
target
, which is"01"
. This represents the two possible alternating patterns we aim to match: “010101... ” or “101010... ”.Then, we calculate the initial flips to determine how many flips are required to match the input string
s
to the"01"
pattern. The initial flips are determined by taking the sum of flips by checking each character ins
against the corresponding character in the"01"
pattern using(i % 2)
to handle the alternating sequence.We calculate the minimum flips by taking
min(initialflips,n−initialflips) . Here,n−initialflips , represents the number of flips for the other pattern, which is just the inverse:"10"
.We iterate over all cyclic permutations of the string
s
. We consider every possible starting point of the string by treating the first character as if it is moved to the end in each iteration. During each iteration, we do the following:The count of flips is adjusted for the shifted pattern.
The number of flips required is recalculated by removing the flip count of the outgoing character (
s[i]
) and adding the flip count for the new character appearing at the end of the string after the shift.The minimum flips are updated with the minimum value between the current minimum flips and initial flips, and
n−initialflips to ensure we always track the fewest flips required.
After iterating over and evaluating all cyclic permutations, we return the final value of the minimum number of flips required to make the string alternating.
Let’s look at the following illustration to better understand the solution.