String Compression II - Problem

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.

Input & Output

Example 1 — Basic Compression
$ Input: s = "aaabcccd", k = 2
Output: 4
💡 Note: Delete 'b' and one 'c' to get "aaaccd" which compresses to "a3c2d" (length 4)
Example 2 — Single Character Run
$ Input: s = "aabbaa", k = 2
Output: 2
💡 Note: Delete the two 'b's to get "aaaa" which compresses to "a4" (length 2)
Example 3 — No Compression Benefit
$ Input: s = "ababacb", k = 0
Output: 7
💡 Note: No deletions allowed, each character is single so compressed length equals original length

Constraints

  • 1 ≤ s.length ≤ 100
  • 0 ≤ k ≤ s.length
  • s contains only lowercase English letters

Visualization

Tap to expand
String Compression II: Strategic Character DeletionInput: s = "aaabcccd", k = 21. Original String:aaabcccdDELETEDELETE2. After Deletions:aaaccdString: "aaaccd"3. Run-length Encoding:a3c2dFinal Compressed Length: 4Key Strategy:• Delete 'b' to avoid breaking 'a' run• Delete one 'c' to create 'c2' instead of 'c1c1'• Use k=2 deletions optimallyCompression Savings:Original: "a3bc3d" → length 5Optimized: "a3c2d" → length 4
Understanding the Visualization
1
Input Analysis
Original string with scattered identical characters
2
Strategic Deletion
Remove characters to create longer runs of same characters
3
Compression
Apply run-length encoding to get minimum length
Key Takeaway
🎯 Key Insight: Strategic deletion of characters can create longer consecutive runs, leading to better compression ratios than the original string.
Asked in
Google 15 Facebook 12 Amazon 8
28.5K Views
Medium Frequency
~35 min Avg. Time
856 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen