Skip to content

1758. Minimum Changes To Make Alternating Binary String 👍

  • Time: $O(n)$
  • Space: $O(1)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
class Solution {
 public:
  int minOperations(string s) {
    int cost10;  // the cost to make s "1010"

    for (int i = 0; i < s.length(); ++i)
      if (s[i] - '0' == i % 2)
        ++cost10;

    const int cost01 = s.length() - cost10;  // the cost to make s "0101"
    return min(cost10, cost01);
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
class Solution {
  public int minOperations(String s) {
    int cost10 = 0; // the cost to make s "1010"

    for (int i = 0; i < s.length(); ++i)
      if (s.charAt(i) - '0' == i % 2)
        ++cost10;

    final int cost01 = s.length() - cost10; // the cost to make s "0101"
    return Math.min(cost10, cost01);
  }
}
1
2
3
4
5
6
7
class Solution:
  def minOperations(self, s: str) -> int:
    # the cost to make s "1010"
    cost10 = sum(int(c) == i % 2 for i, c in enumerate(s))
    # the cost to make s "0101"
    cost01 = len(s) - cost10
    return min(cost10, cost01)