Minimum Number of Changes to Make Binary String Beautiful

You are given a 0-indexed binary string `s` of even length. The string is **beautiful** if it can be cut into one or more substrings such that every substring has even length and contains only `0`s or only `1`s. In one change you may set any character of `s` to `0` or `1`. Return the minimum number of changes needed to make `s` beautiful.

30:00

Minimum Number of Changes to Make Binary String Beautiful
medium
Free written solution
Topics
Companies

You are given a 0-indexed binary string s of even length.

The string is beautiful if it can be cut into one or more substrings such that every substring has even length and contains only 0s or only 1s.

In one change you may set any character of s to 0 or 1. Return the minimum number of changes needed to make s beautiful.

Example 1:
Input: {"s":"1001"}
Output: 2
Constraints:
  • 2≤s.length≤1052 \leq s.length \leq 10^5

  • s has an even length.

  • s[i] is either 0 or 1.

Test Cases
Input (Stdin)
Expected Output (Stdout)
Execution Result

Run code to see results.

Input
arr ={"s":"1001"}

Any even block of equal bits is made of 2-character blocks of equal bits, so it is enough to make every aligned pair (s[0]s[1], s[2]s[3], ...) uniform. There are 2 pairs.

s cut into aligned pairs

0

1
0

.

2

0
1

.

A mixed pair (01 or 10) needs exactly one flip; a uniform pair (00 or 11) needs none. Uniform pairs glue into valid even blocks.

changes

0

pairs checked

0 / 2 (0 mixed)

Variables
VariableValue
changes0
pairs2
DepthFunction Call
Stack empty
0/4