mirror of
https://github.com/Manoj-HV30/dsa-competitive-programming.git
synced 2026-05-16 19:35:22 +00:00
57 lines
1.7 KiB
C++
57 lines
1.7 KiB
C++
class Solution {
|
|
public:
|
|
int minFlips(string s) {
|
|
int n = s.size();
|
|
string t = s + s;
|
|
|
|
int ans = INT_MAX;
|
|
int diff1=0, diff2 = 0;
|
|
for(int i =0;i<t.size();i++){
|
|
char expected1 = (i%2 ? '1':'0');
|
|
char expected2 = (i%2 ? '0':'1');
|
|
|
|
if(t[i]!=expected1) diff1++;
|
|
if(t[i]!=expected2) diff2++;
|
|
|
|
if(i>=n){
|
|
char old = t[i-n];
|
|
char oldExpected1 = ((i-n)%2 ? '1' : '0');
|
|
char oldExpected2 = ((i-n)%2 ? '0' : '1');
|
|
|
|
if(old!=oldExpected1) diff1--;
|
|
if(old!=oldExpected2) diff2--;
|
|
|
|
|
|
}
|
|
if(i>=n-1)
|
|
ans = min(ans, min(diff1,diff2));
|
|
|
|
}
|
|
return ans;
|
|
}
|
|
};
|
|
|
|
//SC : o(n) TC : o(n)
|
|
|
|
|
|
/*
|
|
Approach:
|
|
Since the string can be rotated, we simulate all possible rotations by
|
|
doubling the string (t = s + s). Any rotation of s will appear as a
|
|
substring of length n in this doubled string. We then slide a window of
|
|
size n across t and compute how many flips are required to make the
|
|
current window alternating.
|
|
|
|
There are only two possible alternating patterns: "010101..." and
|
|
"101010...". We maintain two mismatch counters (diff1 and diff2) that
|
|
track how many characters in the current window differ from each pattern.
|
|
As the window expands, we add the mismatch contribution of the new
|
|
character. When the window exceeds size n, we remove the contribution of
|
|
the character that leaves the window.
|
|
|
|
For every window of size n, the minimum of diff1 and diff2 gives the
|
|
number of flips required for that rotation. We keep track of the global
|
|
minimum across all windows.
|
|
|
|
*/
|