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 i and invert all characters from index 0 to index i (both inclusive), with a cost of i + 1
  • Choose an index i and invert all characters from index i to index n - 1 (both inclusive), with a cost of n - 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
Minimum Cost to Make All Characters EqualExample: s = "0011" → Output: 10011Input StringTransition PointCharacters differ: 0 ≠ 1Left OperationRight OperationCost: 3Cost: 1 ← Cheaper!Minimum Cost = 1
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
Asked in
Google 25 Meta 18 Amazon 15
12.8K Views
Medium Frequency
~15 min Avg. Time
456 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