Skip to main content
LeetCode 1531, Hard. Topics: String, Dynamic Programming. View on LeetCode. Generate this problem as a practice environment: tested reference solution, 22 parametrized pytest cases, and a playground notebook:

Problem

<a href=“http://en.wikipedia.org/wiki/Run-length_encoding”>Run-length encoding</a> 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 <code>“aabccc”</code> we replace <code>“aa”</code> by <code>“a2”</code> and replace <code>“ccc”</code> by <code>“c3”</code>. Thus the compressed string becomes <code>“a2bc3”</code>. Notice that in this problem, we are not adding <code>‘1’</code> after single characters. Given a string <code>s</code> and an integer <code>k</code>. You need to delete <strong>at most</strong> <code>k</code> characters from <code>s</code> such that the run-length encoded version of <code>s</code> has minimum length. Find the <em>minimum length of the run-length encoded version of </em><code>s</code><em> after deleting at most </em><code>k</code><em> characters</em>.

Examples

Constraints

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

Solution

Reference implementation from solution.py on GitHub, full suite in test_solution.py:

Complexity

Tags

NeetCode All.
Last modified on September 7, 2026