← Questions

Shortest run-length encoding after deleting k characters

0
DatabricksCodingLast asked Feb 2026

A coding interview question asked in Databricks's technical phone screen, last asked Feb 2026. It tests dynamic programming, strings and run-length encoding.

Run-length encoding replaces each run of a repeated character with the character followed by the run's length, and writes no number for a run of length 1. So "aaabcc" becomes "a3bc2" and "aaaaaaaaaaaa" becomes "a12". Given a string and an integer k, delete at most k characters so that the encoded string is as short as possible, and return that length.

Interface

Unless you agree on a different interface with the interviewer, assume:

  • min_encoded_length(s: str, k: int) -> int.

Example

min_encoded_length("aaabcccd", 2)     ->  4    # delete "b" and "d": "aaaccc" -> "a3c3"
min_encoded_length("aabbaa", 2)       ->  2    # delete both "b": "aaaa" -> "a4"
min_encoded_length("aaaaaaaaaaa", 0)  ->  3    # "a11"
min_encoded_length("aaabcc", 0)       ->  5    # "a3bc2"

Constraints

  • 1 <= len(s) <= 100, 0 <= k <= len(s), lowercase letters only.

Clarifying questions

  • Is a run of length 1 written without a number? (Yes.)
  • Is it at most k deletions, or exactly k?
  • Can the string contain digits? (Then the encoding would be ambiguous.)

What a strong answer covers

  • Why greedy fails: deleting characters can merge two runs of the same letter, as in "aabbaa", and the length of a run's number changes only at 2, 10 and 100.
  • A DP dp(i, k) = the shortest encoding of s[i:] with k deletions left. Either delete s[i], or make s[i] start a run: scan j forward, keep the characters equal to s[i], delete the others (as long as deletions remain), and add the run's encoded length plus dp(j + 1, k - deleted).
  • The encoded length of a run of c: 1 for c = 1, 2 for 2 to 9, 3 for 10 to 99, 4 for 100.
  • Cost: O(n² · k) time, O(n · k) states.
  • Tests: k = 0, k = len(s) (answer 0), runs crossing the 9/10 boundary.

Follow-ups

  • Return the string after the deletions, not only the length.
  • Deletions have different costs per character, with a budget.
  • You may also insert characters. What changes?

Where it's asked

What it tests

dynamic programming · strings · run-length encoding

Write and test your solution herePython in your browser, the question's tests level by level, every submission kept for you.Sign in to start coding