You are given a binary string s. You are allowed to perform two types of operations on the string in any sequence:
s and append it to the end of the string.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.
"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 <= 105s[i] is either '0' or '1'.One efficient approach is to use a sliding window to determine the number of flips required for each substring of length equal to the original string.
For a binary string to be alternating, it can follow two patterns: '010101...' (starting with '0') and '101010...' (starting with '1'). We can employ a combination of the two permitted operations: character removal and appending, and character flipping, to transform the string into one of those patterns with the minimum number of flips.
This solution attempts both alternating patterns using a sliding window over a string doubled to simulate rotations. It counts mismatches for both patterns, adjusting counts when the window slides.
Java
C++
C#
JavaScript
Time Complexity: O(n)
Space Complexity: O(n)
Another approach is to use a greedy strategy based on calculating mismatches directly without explicitly considering rotations. This involves calculating mismatches for two possible alternating patterns from the start and adjusting for the effect of rotations. This can be achieved by maintaining two mismatch counters for the two patterns and adjusting them based on the original string and its windowed variants.
This greedy approach initializes mismatch counts for both patterns. It calculates these mismatches over the length of the input string and then chooses the minimum of both as the answer.
Java
C++
C#
JavaScript
Time Complexity: O(n)
Space Complexity: O(1)
| Approach | Complexity |
|---|---|
| Sliding Window with Rotations | Time Complexity: O(n) |
| Greedy Approach | Time Complexity: O(n) |
Minimum Number of Flips to make Binary String Alternating - Sliding Window - Leetcode 1888 - Python • NeetCode • 47,745 views views
Watch 9 more video solutions →Practice Minimum Number of Flips to Make the Binary String Alternating with our built-in code editor and test cases.
Practice on FleetCodePractice this problem
Open in Editor