Minimum Number of Changes to Make Binary String Beautiful - Problem

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

A string is beautiful if it's possible to partition it into one or more substrings such that:

  • Each substring has an even length
  • Each substring contains only 1's or only 0's

You can change any character in s to 0 or 1.

Return the minimum number of changes required to make the string s beautiful.

Input & Output

Example 1 — Basic Case
$ Input: s = "1001"
Output: 2
💡 Note: We can partition into pairs: "10" and "01". First pair needs 1 change (10→00 or 10→11), second pair needs 1 change (01→00 or 01→11). Total: 2 changes.
Example 2 — No Changes Needed
$ Input: s = "10"
Output: 1
💡 Note: Only one pair "10" where characters differ, so we need 1 change to make it "00" or "11".
Example 3 — Already Beautiful
$ Input: s = "1100"
Output: 0
💡 Note: We can partition as "11" and "00". Both substrings already contain identical characters, so 0 changes needed.

Constraints

  • 2 ≤ s.length ≤ 105
  • s has even length
  • s consists only of '0' and '1'

Visualization

Tap to expand
Minimum Changes for Beautiful Binary String INPUT Binary String s: 1 idx 0 0 idx 1 0 idx 2 1 idx 3 Pair 1 "10" Pair 2 "01" Properties: - Length: 4 (even) - Must partition into even-length substrings - Each substring: all 0s or all 1s s = "1001" ALGORITHM STEPS 1 Process Pairs Check adjacent chars at positions (0,1), (2,3)... 2 Compare Pair (0,1) s[0]='1', s[1]='0' Different! changes++ 1 0 +1 change 3 Compare Pair (2,3) s[2]='0', s[3]='1' Different! changes++ 0 1 +1 change 4 Sum Changes Total = 1 + 1 = 2 Count mismatched pairs FINAL RESULT Beautiful String Options: Option A: "1100" "11" + "00" (both uniform) Option B: "0011" "00" + "11" (both uniform) Changes needed: 1 --> 0 or 1 1 --> 0 or 1 Output: 2 Minimum changes Key Insight: For a string to be "beautiful", each pair of adjacent characters (at even-odd indices) must be identical. The greedy approach checks pairs at positions (0,1), (2,3), (4,5)... If a pair differs, we need exactly 1 change to make them equal. Time: O(n), Space: O(1). We don't need to track which char to change to! TutorialsPoint - Minimum Number of Changes to Make Binary String Beautiful | Greedy Approach
Asked in
Google 15 Meta 12 Microsoft 8
8.9K Views
Medium Frequency
~15 min Avg. Time
432 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen