#2712

Minimum Cost to Make All Characters Equal

Medium
StringDynamic ProgrammingGreedyDynamic ProgrammingPrefix SumSuffix Sum
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(n)
💡

Intuition

Time O(n)Space O(n)

The optimal approach calculates the cost to make all characters equal by leveraging prefix and suffix operations. This reduces the number of operations needed to find the minimum cost significantly.

⚙️

Algorithm

4 steps
  1. 1Step 1: Create two arrays, prefix and suffix, to store the cost of making the prefix and suffix equal to '0' and '1'.
  2. 2Step 2: Fill the prefix array by iterating through the string and calculating the cost of converting the prefix to '0' and '1'.
  3. 3Step 3: Fill the suffix array similarly for the suffix.
  4. 4Step 4: Calculate the minimum cost by combining the prefix and suffix costs.
solution.py12 lines
1def minCost(s):
2    n = len(s)
3    prefix_cost = [0] * n
4    suffix_cost = [0] * n
5    for i in range(n):
6        prefix_cost[i] = (prefix_cost[i - 1] if i > 0 else 0) + (i + 1 if s[i] == '1' else 0)
7    for i in range(n - 1, -1, -1):
8        suffix_cost[i] = (suffix_cost[i + 1] if i < n - 1 else 0) + (n - i if s[i] == '0' else 0)
9    min_cost = float('inf')
10    for i in range(n):
11        min_cost = min(min_cost, prefix_cost[i] + suffix_cost[i])
12    return min_cost

Complexity note: The complexity is O(n) because we make a single pass to compute the prefix costs and another to compute the suffix costs, resulting in linear time complexity.

  • 1Understanding the cost of operations is crucial for minimizing the total cost.
  • 2Breaking the problem into prefix and suffix calculations helps in optimizing the solution.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.