#3784
Minimum Deletion Cost to Make All Characters Equal
MediumArrayHash TableStringEnumerationHash MapArray
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(1) |
💡
Intuition
Time O(n)Space O(1)
Group characters and keep the one with the highest deletion cost. The rest will be deleted to minimize total cost.
⚙️
Algorithm
3 steps- 1Step 1: Initialize variables to track the current character and total deletion cost.
- 2Step 2: Iterate through the string, summing costs of characters that are not the current character.
- 3Step 3: Update the minimum cost by comparing with the total cost for each character.
solution.py10 lines
1def minCost(s, cost):
2 total_cost = 0
3 max_cost = 0
4 current_char = s[0]
5 for i in range(len(s)):
6 if s[i] == current_char:
7 max_cost = max(max_cost, cost[i])
8 else:
9 total_cost += cost[i]
10 return total_cost + (sum(cost) - max_cost)ℹ
Complexity note: Single pass through the string results in linear complexity.
- 1Keep the character with the highest deletion cost.
- 2Sum costs of characters to be deleted.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.