Shortest run-length encoding after deleting k characters
I was asked this
No reports yet. Sign in to say where you were asked it.
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
kdeletions, or exactlyk? - 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 ofs[i:]withkdeletions left. Either deletes[i], or makes[i]start a run: scanjforward, keep the characters equal tos[i], delete the others (as long as deletions remain), and add the run's encoded length plusdp(j + 1, k - deleted). - The encoded length of a run of
c: 1 forc = 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
- Databricks · Technical phone screen · Last asked Feb 202660 min · Live coding in CoderPad or a similar runnable editor
What it tests
dynamic programming · strings · run-length encoding
No official answer yet. Write yours on the right and run it.
Nothing published yet.
Sign in to submit your code; every attempt is kept here.
