String Compression II Problem
Description
LeetCode Problem 1531.
Run-length encoding is a string compression method that works by replacing consecutive identical characters (repeated 2 or more times) with the concatenation of the character and the number marking the count of the characters (length of the run). For example, to compress the string "aabccc" we replace "aa" by "a2" and replace "ccc" by "c3". Thus the compressed string becomes "a2bc3".
Notice that in this problem, we are not adding '1' after single characters.
Given a string s and an integer k. You need to delete at most k characters from s such that the run-length encoded version of s has minimum length.
Find the minimum length of the run-length encoded version of s after deleting at most k characters.
Example 1:
Input: s = "aaabcccd", k = 2
Output: 4
Explanation: Compressing s without deleting anything will give us "a3bc3d" of length 6. Deleting any of the characters 'a' or 'c' would at most decrease the length of the compressed string to 5, for instance delete 2 'a' then we will have s = "abcccd" which compressed is abc3d. Therefore, the optimal way is to delete 'b' and 'd', then the compressed version of s will be "a3c3" of length 4.
Example 2:
Input: s = "aabbaa", k = 2
Output: 2
Explanation: If we delete both 'b' characters, the resulting compressed string would be "a4" of length 2.
Example 3:
Input: s = "aaaaaaaaaaa", k = 0
Output: 3
Explanation: Since k is zero, we cannot delete anything. The compressed string is "a11" of length 3.
Constraints:
1 <= s.length <= 1000 <= k <= s.lengthscontains only lowercase English letters.
Solution
Approach: Dynamic Programming over Runs
Let dp[i][j] be the length of the shortest encoding of the suffix s[i:] when we may still delete up to j characters. The answer is dp[0][k], and dp[n][j] = 0 for every j (an empty suffix encodes to nothing, and unused deletions are fine because the limit is "at most").
For s[i] there are two choices:
- Delete it, if
j > 0: costdp[i + 1][j - 1]. - Keep it as the first letter of a run. The run is made of copies of
s[i]; walktfromito the right, countingsamecopies ofs[i]anddeletedother letters, which we must remove to keep the run together. Each times[t] == s[i], the run can end att, costingrunLength(same) + dp[t + 1][j - deleted]. Stop as soon asdeleted > j.
runLength(c) is the length of one run of c letters: 1 for a single letter, 2 for 2 to 9, 3 for 10 to 99, and 4 for 100.
Why is it enough to only end runs at copies of s[i]? Ending a run at a different letter would mean we kept that letter in the run, which is impossible, and any letters after the last kept copy belong to the next part, which dp[t + 1] already handles. The case to watch is a long run: going from 9 to 10 copies, or from 99 to 100, costs an extra digit, so sometimes deleting one copy of the run itself is best ("a" * 100 with k = 1 gives "a99", length 3). The "delete it" choice covers that.
Complexity: O(n2 * k) time and O(n * k) space, where n is the length of s. Here that is at most about 106 steps.
class Solution:
def getLengthOfOptimalCompression(self, s: str, k: int) -> int:
def run_length(count): # length of "c", "c7", "c42" or "c100"
return 1 if count == 1 else 2 if count < 10 else 3 if count < 100 else 4
n = len(s)
INF = float("inf")
# dp[i][j] = shortest encoding of s[i:] when we may still delete j characters
dp = [[0] * (k + 1) for _ in range(n + 1)]
for i in range(n - 1, -1, -1):
for j in range(k + 1):
best = dp[i + 1][j - 1] if j > 0 else INF # delete s[i]
# Keep s[i] and grow its run to s[t], deleting the other letters in between.
same = deleted = 0
for t in range(i, n):
if s[t] == s[i]:
same += 1
best = min(best, run_length(same) + dp[t + 1][j - deleted])
else:
deleted += 1
if deleted > j:
break
dp[i][j] = best
return dp[0][k]