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: 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
Minimum Cost to Make All Characters Equal INPUT Binary String s = "0011" i=0 i=1 i=2 i=3 0 0 1 1 Two Operations: Op 1: Invert [0..i] Cost = i + 1 Flip from start to i Op 2: Invert [i..n-1] Cost = n - i Flip from i to end Goal: Make all chars equal "0000" or "1111" ALGORITHM STEPS 1 Find Transition Points Where s[i] != s[i-1] 0 0 | 1 1 Transition at i=2 (s[1]=0, s[2]=1) 2 Calculate Both Costs For each transition point At i=2: n=4 Left cost: i = 2 Right cost: n-i = 4-2 = 2 3 Choose Minimum min(left, right) at each min(2, 2) = 2 But we can do better! 4 Greedy Choice Op1 at i=1: cost = 1+1 = 2 Actually: Op2 at i=2, cost=1 FINAL RESULT Original: "0011" 0 0 1 1 Apply Op2 at i=2 Invert [2..3], Cost = 4-2 = 2 Better: Op1 at i=0 Invert [0..0], Cost = 0+1 = 1 Result: "1011" ---> more ops 0 0 0 0 Output: 1 Key Insight: At each transition point (where adjacent characters differ), we must perform an operation. Greedy approach: For each transition at index i, choose min(i, n-i) - the cheaper operation. Total minimum cost = sum of min costs at all transition points. Time: O(n), Space: O(1). TutorialsPoint - Minimum Cost to Make All Characters Equal | Greedy Two-Pass Solution
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