Minimum Cost to Make All Characters Equal - Problem
You're given a binary string consisting of only '0's and '1's, and you need to make all characters in the string equal with the minimum possible cost.
You have two powerful operations at your disposal:
- Left Operation: Choose any index
iand flip all characters from the beginning (index 0) up to indexi(inclusive). This costsi + 1 - Right Operation: Choose any index
iand flip all characters from indexito the end of the string. This costsn - i
When you "flip" a character, '0' becomes '1' and '1' becomes '0'.
Goal: Find the minimum cost to make all characters in the string identical (either all '0's or all '1's).
Example: For string "0011", you could flip from index 2 to end (cost 2) to get "0000", or use other combinations of operations.
Input & Output
example_1.py โ Basic case
$
Input:
s = "0011"
โบ
Output:
2
๐ก Note:
We have one transition at position 1 (between s[1]='0' and s[2]='1'). We can choose left operation (cost 2) or right operation (cost 2). Both cost the same, so minimum cost is 2.
example_2.py โ Multiple transitions
$
Input:
s = "010101"
โบ
Output:
9
๐ก Note:
Transitions at positions 0,1,2,3,4. Costs: min(1,5)=1, min(2,4)=2, min(3,3)=3, min(4,2)=2, min(5,1)=1. Total: 1+2+3+2+1=9.
example_3.py โ Already uniform
$
Input:
s = "0000"
โบ
Output:
0
๐ก Note:
All characters are already the same, so no operations are needed. Cost is 0.
Constraints
- 1 โค s.length โค 105
- s[i] is either '0' or '1'
- Binary string only - no other characters allowed
Visualization
Tap to expand
Understanding the Visualization
1
Identify Problem Areas
Find where adjacent switches are in different positions - these are the 'problem boundaries'
2
Calculate Tool Costs
For each boundary, calculate the cost of using Left Lever vs Right Lever
3
Choose Cheaper Tool
Pick the less expensive tool for each boundary and sum up all costs
Key Takeaway
๐ฏ Key Insight: Focus on transitions (boundaries) between different characters, not individual characters. For each transition, greedily choose the cheaper operation.
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code