926.Flip String to Monotone Increasing || Leetcode

Leetcode(POTD) Official
1 min readJan 17, 2023

This solution uses two variables, “zeroes” and “ones”, to keep track of the number of 0’s and 1’s in the string, respectively. It then iterates through the string, updating the count of 0’s and 1’s as it goes along. At each position, it compares the minimum number of flips needed to make the string monotone increasing by comparing the number of 0’s and 1’s on the left and right of the current position in the string.

int minFlipsMonoIncr(string s) {
int zeroes = 0, ones = 0;
for (char c : s) {
if (c == '0') {
zeroes++;
}
}
int res = zeroes;
for (int i = 0; i < s.length(); i++) {
if (s[i] == '0') {
zeroes--;
} else {
ones++;
}
res = min(res, ones + zeroes);
}
return res;
}

This solution is more optimized as it only iterates through the string once. It’s O(n) time complexity and O(1) space complexity which is more efficient than the previous solution.

--

--

Leetcode(POTD) Official

"Unlock the full potential of your coding skills with Leetcode's POTD (Problem of the Day) official blog channel.Our comprehensive approach to problem-solving