#1531

String Compression II

Hard
StringDynamic ProgrammingDynamic ProgrammingGreedy Algorithms
LeetCode ↗

Approaches

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

Intuition

Time O(n² * k)Space O(n * k)

The optimal solution uses dynamic programming to efficiently compute the minimum length of the run-length encoded string after deleting up to k characters. It builds on the idea of keeping track of the current index and the remaining deletions, leveraging previously computed results to avoid redundant calculations.

⚙️

Algorithm

3 steps
  1. 1Step 1: Initialize a DP table where dp[i][j] represents the minimum compressed length of the substring s[0:i] with j deletions allowed.
  2. 2Step 2: For each character in the string, calculate the compressed length considering the current character and the previous runs.
  3. 3Step 3: Update the DP table based on whether to delete characters or keep them, ensuring to consider the run-length encoding.
solution.py28 lines
1def get_compressed_length(s, start, end):
2    length = 0
3    count = 0
4    for i in range(start, end + 1):
5        count += 1
6        if i == end or s[i] != s[i + 1]:
7            length += 1 + (len(str(count)) if count > 1 else 0)
8            count = 0
9    return length
10
11def compress_string(s, k):
12    n = len(s)
13    dp = [[float('inf')] * (k + 1) for _ in range(n + 1)]
14    dp[0][0] = 0
15    for i in range(1, n + 1):
16        for j in range(k + 1):
17            dp[i][j] = dp[i - 1][j] + 1
18            count = 0
19            for m in range(i - 1, -1, -1):
20                count += 1
21                if m < i - 1 and s[m] != s[i - 1]:
22                    break
23                if j - (count - 1) >= 0:
24                    dp[i][j] = min(dp[i][j], dp[m][j - (count - 1)] + get_compressed_length(s, m, i - 1))
25    return dp[n][k]
26
27# Example usage:
28print(compress_string('aaabcccd', 2))  # Output: 4

Complexity note: The time complexity is O(n² * k) because we iterate through the string and for each character, we may consider all previous characters, while also considering up to k deletions.

  • 1Understanding run-length encoding is crucial for solving this problem.
  • 2Dynamic programming can significantly reduce the complexity by avoiding redundant calculations.

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