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:
2
💡 Note:
There's one transition at position 1 (between s[1]='0' and s[2]='1'). To eliminate this transition, we can use either a left operation at index 1 (cost = 2) or right operation at index 2 (cost = 2). The minimum cost is 2.
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
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code