Crash Code Part-12 (Letter Candles Minimum Cost)
Solve the Letter Candles algorithm problem in Python, with efficient O(N+M) greedy approach to minimize character frequency sum of squares with step-by-step code
568 Words [Mind Tax: 2:34m]
15 September 2026, 6:30:00 PM
Problem Description & Examples
Your friend Alice has a box with N letter candles in it. The cost of the box is determined as follows: Find the number of occurrences of each characters in the box and sum up the squares of these numbers.
Alice wants to reduce the cost of the box by removing some candles from it. However, she is allowed to remove at most M candles from the box. Can you help Alice determine the minimum cost of the box?
Input
- Line 1: Integer N, representing the number of letter candles.
- Line 2: Integer M, representing the number of candles Alice can remove.
- Line 3: N-lettered string S, which contains lowercase English letters, representing the letter candles in the box.
Output:
Print the minimum possible cost of the box.
Example Case:
- Input: N=6, M=2, S=bacacc
- Output: 6
- Explanation: There are two As, one B, and three Cs. The current cost is 2^2 + 1^2 + 3^2 = 14. The best way to minimize cost is to remove two C-shaped candles. The new minimal cost will be 2^2 + 1^2 + 1^2 = 6.
Approach & Theory
To minimize the sum of squares, you must greedily reduce the highest frequency character. Reducing a larger number decreases the square sum much more than reducing a smaller number.
Since the string only contains lowercase English letters, there are at most 26 unique characters. We can count the frequencies, extract them into a list, and repeatedly find and decrement the maximum value up to M times.
Solution
| |
Complexity Analysis
- Time Complexity: O(N + M). Counting string frequencies takes O(N) time. Finding the maximum frequency takes at most 26 operations, repeated M times, which simplifies to O(M).
- Space Complexity: O(1). The dictionary and list store a maximum of 26 integer frequencies, using constant extra memory.