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
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.
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code