Leetcode 1758. Minimum Changes To Make Alternating Binary String
The problem is to determine the minimum number of changes needed to make a given binary string an alternating binary string. An alternating binary string is a string where no two adjacent characters are the same, i.e., it follows a pattern like “010101” or “101010”.
Given a binary string s
, you need to return the minimum number of changes needed to make the string alternating.
s
is between 1
and 100,000
.To solve this problem efficiently:
s
into two possible alternating patterns:
Here’s the C++ implementation of the solution:
#include <iostream>
#include <string>
#include <algorithm>
int minChangesToMakeAlternatingBinaryString(std::string s) {
int n = s.length();
int count1 = 0, count2 = 0;
for (int i = 0; i < n; ++i) {
if ((i % 2 == 0 && s[i] != '0') || (i % 2 == 1 && s[i] != '1')) {
count1++;
}
if ((i % 2 == 0 && s[i] != '1') || (i % 2 == 1 && s[i] != '0')) {
count2++;
}
}
return std::min(count1, count2);
}
int main() {
std::string s = "0100100010";
std::cout << "Minimum changes to make the string alternating: "
<< minChangesToMakeAlternatingBinaryString(s) << std::endl;
return 0;
}
count1
and count2
, to keep track of mismatches for Pattern1 and Pattern2 respectively.The time complexity of this solution is O(n)
where n
is the length of the string. This is because we are making a single pass through the string to check each character against both patterns.
The space complexity is O(1)
as we are using a constant amount of extra space regardless of the input size.
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?