Minimum Cost to Make All Characters Equal - Problem
You are given a 0-indexed binary string s of length n on which you can apply two types of operations:
- Choose an index
iand invert all characters from index0to indexi(both inclusive), with a cost ofi + 1 - Choose an index
iand invert all characters from indexito indexn - 1(both inclusive), with a cost ofn - i
Return the minimum cost to make all characters of the string equal.
Invert a character means if its value is '0' it becomes '1' and vice-versa.
Input & Output
Example 1 — Basic Case
$
Input:
s = "0011"
›
Output:
1
💡 Note:
There's one transition at position 1 (0→1). We can fix this with a right operation at index 2 with cost n-i = 4-2 = 2, or left operation at index 1 with cost i+1 = 2. Actually, the optimal is right operation at index 2 costing 2, but we can do better with right operation at index 3 costing 1 to make all 0s.
Example 2 — All Same
$
Input:
s = "1111"
›
Output:
0
💡 Note:
All characters are already equal, so no operations needed. Cost = 0.
Example 3 — Multiple Transitions
$
Input:
s = "010"
›
Output:
2
💡 Note:
Two transitions: at positions 0 (0→1) and 1 (1→0). For each transition, we choose the cheaper operation. Total cost = min(1,2) + min(2,1) = 1 + 1 = 2.
Constraints
- 1 ≤ s.length ≤ 105
- s consists only of '0' and '1'
Visualization
Tap to expand
Understanding the Visualization
1
Input
Binary string with mixed 0s and 1s
2
Find Transitions
Identify positions where adjacent characters differ
3
Choose Operations
For each transition, pick cheaper flip operation (left or right)
Key Takeaway
🎯 Key Insight: Only transition points between different characters matter - fix each with the cheaper operation
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code