leetcode

Leetcode Solutions (0x6A73)
git clone https://git.pngu.org/leetcode
Log | Files | Refs | Submodules | README

commit 805837bb0add796598723c64d8a5fb1362194e0f
parent 3cd1b5564145691e318084324b1c7827181ba79b
Author: Jack Sangdahl <jack@pngu.org>
Date:   Wed,  4 Mar 2026 20:44:09 -0700

1758. minimum changes to make alternating binary string

Diffstat:
Mmin_change_alt_binary_str.c | 24++++++++++++++----------
Mmin_change_alt_binary_str.py | 26+++++---------------------
2 files changed, 19 insertions(+), 31 deletions(-)

diff --git a/min_change_alt_binary_str.c b/min_change_alt_binary_str.c @@ -1,5 +1,7 @@ // 1758. Minimum Changes To Make Alternating Binary String #include "leetcode.h" +#include <math.h> +#include <string.h> /* * given a string 's' consisting only of the characters '0' and '1', in one @@ -10,19 +12,21 @@ */ int minOperations(char *s) { - int n = strlen(s), cnt = 0; - for (int i = 0; i < n; i++) { - if (!(i % 2) && s[i] == '1') - cnt++; - else if (i % 2 && s[i] == '0') - cnt++; - } + int cnt = 0, n = strlen(s); + for (int i = 0; i < n; i++) + cnt += (s[i] ^ i) & 1; return fmin(cnt, n - cnt); } int main() { char *s1 = "0100", *s2 = "10", *s3 = "1111"; - printf("%d\n", minOperations(s1)); // expect: 1 - printf("%d\n", minOperations(s2)); // expect: 0 - printf("%d\n", minOperations(s3)); // expect: 2 + int r1 = minOperations(s1); + int r2 = minOperations(s1); + int r3 = minOperations(s1); + printf("%d\n", r1); // expect: 1 + assert(r1 == 1); + printf("%d\n", r2); // expect: 0 + assert(r2 == 1); + printf("%d\n", r3); // expect: 2 + assert(r3 == 1); } diff --git a/min_change_alt_binary_str.py b/min_change_alt_binary_str.py @@ -9,27 +9,11 @@ number of operations needed to make 's' alternating. """ -class Solution(object): - def count(self, s, pre): - cnt = 0 - for i in range(1, len(s)): - curr = s[i] - if curr == pre: - cnt += 1 - pre = "0" if pre == "1" else "1" - else: - pre = curr - return cnt - - def minOperations(self, s): - """ - :type s: str - :rtype: int - """ - c0 = s[0] - cnt1 = self.count(s, c0) - cnt2 = self.count(s, "0" if c0 == "1" else "1") + 1 - return min(cnt1, cnt2) +class Solution: + def minOperations(self, s: str) -> int: + return min( + cnt := sum((i & 1) == (ord(j) & 1) for i, j in enumerate(s)), len(s) - cnt + ) if __name__ == "__main__":