Files
dsa-competitive-programming/leetcode/lc1758.cpp
T

26 lines
1.4 KiB
C++

class Solution{
public:
int minOperations(string s){
int start0=0,start1=0;
for(int i =0;i<s.size();i++){
if(i%2==0){
if(s[i]=='1') start0++;
else start1++;
}
else{
if(s[i]=='1') start1++;
else start0++;
}
}
return min(start0, start1);
}
}
//TC: o(n), SC: o(1)
//It has a brute force approach where we construct both 0-start-alternating and 1-start-alternating string and count differences for each, compared to the string s, and return min of the count of differences. It takes o(n) space complexity
//here the core idea is that a binary string can be alternating in only two possible patterns: one starting with 0 (010101...) and the other starting with 1 (101010...). The algorithm scans the string once and counts how many characters do not match each of these patterns. For every index, it checks whether the character fits the expected value for both cases (start with 0 and start with 1) and increments the corresponding counter when there is a mismatch, which represents a flip operation. By the end of the loop, we know the number of flips required to convert the string into each alternating pattern, and the minimum of these two counts gives the minimum operations needed.