Minimum Cost to Make All Characters Equal — Medium Problem & Solution
You are given a binary string s of length n. Two kinds of operation are available, and you may use them any number of times: Choose an index i and invert…
- Difficulty: Medium
- Topics: Strings, Dynamic Programming, Greedy
- Asked at: Amazon, Google
- Time limit: 2 s
- Memory limit: 256 MB
- Languages: JavaScript, TypeScript, Python, Java, C++, C, C#, Go, Kotlin, Swift, Rust, PHP and Ruby
Problem statement
You are given a binary string s of length n. Two kinds of operation are available, and you may use them any number of times:
- Choose an index
iand invert every character from index0toi(inclusive). This costsi + 1. - Choose an index
iand invert every character from indexiton - 1(inclusive). This costsn - i.
Inverting turns '0' into '1' and '1' into '0'. Return the minimum total cost to make all characters of the string equal.
The original allows n up to 10^5; here n <= 5 · 10^4 so the cost fits in a 32-bit integer.
Example 1
Input: s = "0110"
Output: 2
Explanation: Invert the suffix from index 3 (cost 1) and the prefix up to index 0 (cost 1): `1111`.
Example 2
Input: s = "10101"
Output: 6
Example 3
Input: s = "1"
Output: 0
Constraints
1 <= s.length == n <= 5 * 10^4s[i] is '0' or '1'
How to solve Minimum Cost to Make All Characters Equal
Only the boundaries between different neighbours matter. A prefix inversion ending at i - 1 or a suffix inversion starting at i toggles exactly the boundary between positions i - 1 and i, so each boundary is paid for separately at min(i, n - i).
Approach
- Set
ans = 0. - For each
ifrom 1 ton - 1withs[i] != s[i - 1], addmin(i, n - i). - Return
ans.
Why it works
Inverting a prefix [0, i-1] (cost i) or a suffix [i, n-1] (cost n - i) changes whether position i - 1 equals position i, and no other adjacent pair. The string is uniform exactly when no boundary remains, so every boundary needs at least one operation at its own position, costing at least min(i, n - i); doing exactly that cheapest one for each boundary achieves the bound.
Complexity
- Time —
O(n) - Space —
O(1)
Pitfalls
- The prefix ending at index
i - 1costsi, noti - 1— mind the off-by-one between index and cost. - It does not matter whether the final string is all zeros or all ones; the boundary count decides.
- Under the original
n <= 10^5the total needs 64 bits.
Reference solution
Python
def minimumCost(s: str) -> int:
n = len(s)
return sum(min(i, n - i) for i in range(1, n) if s[i] != s[i - 1])JavaScript
var minimumCost = function(s) {
var n = s.length, ans = 0;
for (var i = 1; i < n; i++) if (s[i] !== s[i - 1]) ans += Math.min(i, n - i);
return ans;
};Also on the editorial tab: C, C#, C++, Go, Java, Kotlin, PHP, Ruby, Rust, Swift, TypeScript.
All 424 strings problems · the whole catalogue
Learn the technique: Strings · Dynamic Programming