Minimum Number of Changes to Make Binary String Beautiful - Problem

Given a binary string s with an even length, you need to make it beautiful with the minimum number of character changes.

A binary string is considered beautiful if it can be partitioned into one or more substrings where:

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

Goal: Find the minimum number of character flips (0โ†’1 or 1โ†’0) needed to make the string beautiful.

Example: "1001" can become "1100" with 1 change, creating substrings "11" and "00".

Input & Output

example_1.py โ€” Basic Case
$ Input: s = "1001"
โ€บ Output: 2
๐Ÿ’ก Note: We can change "1001" to "1100" by changing positions 2 and 3. This creates two beautiful substrings: "11" and "00". Total changes needed: 2.
example_2.py โ€” Already Beautiful
$ Input: s = "10"
โ€บ Output: 1
๐Ÿ’ก Note: The string "10" needs 1 change to become beautiful. We can change it to "11" or "00", both are valid beautiful strings of even length with homogeneous characters.
example_3.py โ€” Longer String
$ Input: s = "11000111"
โ€บ Output: 1
๐Ÿ’ก Note: Analyzing pairs: (1,1)=same, (0,0)=same, (0,1)=different, (1,1)=same. Only one pair needs changing, so minimum changes = 1.

Constraints

  • 2 โ‰ค s.length โ‰ค 105
  • s.length is even
  • s consists only of characters '0' and '1'

Visualization

Tap to expand
๐ŸŽจ Paint Bucket Organizationโ—โ—‹Pair 1: Mismatch!โ—‹โ—Pair 2: Mismatch!โ—โ—Pair 3: Match! โœ“โ—โ—Fixed Pair 1 โœ“โ—‹โ—‹Fixed Pair 2 โœ“Result: 2 changes needed (one per mismatched pair)
Understanding the Visualization
1
Identify Pairs
Group consecutive buckets into pairs of 2
2
Check Compatibility
See if both buckets in each pair have the same paint color
3
Fix Mismatches
Change one bucket's paint in each mismatched pair
4
Count Changes
Sum up all the paint changes needed
Key Takeaway
๐ŸŽฏ Key Insight: Processing pairs greedily is optimal because any valid beautiful partition must have even-length substrings, and length-2 substrings are the most flexible and require minimal changes.
Asked in
Google 15 Meta 12 Amazon 8 Microsoft 6
23.4K Views
Medium Frequency
~12 min Avg. Time
890 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