Leetcode 1758. Minimum Changes To Make Alternating Binary String
Given a binary string s
, you need to find the minimum number of character flips required to make the string alternating. An alternating binary string is a string where no two adjacent characters are the same. For example, “010101” and “101010” are alternating binary strings. You need to return the minimum number of flips required.
To solve this problem, consider these two possible alternating patterns:
For each pattern, we count the number of positions where the actual character in the string s
does not match the expected character in the pattern. The minimum count between these two results will be the minimum number of flips required to make the string alternating.
Here is the code to implement the solution in Java:
public class MinimumFlipsToAlternatingString {
public int minFlips(String s) {
int n = s.length();
int flips1 = 0; // For pattern '010101...'
int flips2 = 0; // For pattern '101010...'
for (int i = 0; i < n; i++) {
char expectedCharPattern1 = (i % 2 == 0) ? '0' : '1';
char expectedCharPattern2 = (i % 2 == 0) ? '1' : '0';
if (s.charAt(i) != expectedCharPattern1) flips1++;
if (s.charAt(i) != expectedCharPattern2) flips2++;
}
return Math.min(flips1, flips2);
}
public static void main(String[] args) {
MinimumFlipsToAlternatingString solution = new MinimumFlipsToAlternatingString();
System.out.println(solution.minFlips("01001001101")); // Example test case
}
}
The time complexity of this solution is O(n), where n
is the length of the string. This is because we iterate through each character of the string once to evaluate whether it matches the expected character in both potential alternating patterns.
flips1
and flips2
to count mismatches for both patterns.I hope this helps! Let me know if you have any questions.
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?