Shortest Nested Run-Length Encoding of a String
Dynamic ProgrammingAuto-graded · 24 test casesLast updated
Find the shortest nested repeat encoding of a string with interval DP over splits and repeats, using a fixed tie-break order so the output is unique.
Nested Repeat Encoding
You are given a string text. You may shrink it by writing a block of consecutive identical copies compactly as a token.
Token format
A token has the form k{p}:
kis an integer withk >= 2, written in decimal.pis a string, which may itself be an encoded string containing further tokens.- The token stands for the decoded form of
prepeatedktimes in a row.
Tokens and plain characters can be placed next to each other freely, and tokens can be nested, for example 2{a3{b}}.
Task
Return the shortest encoding of text. If no encoding is strictly shorter than text, return text unchanged.
Making the answer unique
Several encodings can have the same minimum length (for instance, ten a characters could be written 10{a} or a9{a}). To get exactly one answer, the encoding of every substring t is defined by the following procedure, and your function must return the result for the whole text.
For a substring t of length L:
- If
L == 1, the encoding istitself. - Otherwise start with the raw candidate
t. - Then examine further candidates in this order:
- Splits: for
m = 1, 2, ..., L-1, the candidate isenc(t[:m]) + enc(t[m:]), whereencis the encoding of each part, defined by this same procedure. - Repeats: for each unit length
d = 1, 2, ..., L-1whereddividesLandtconsists oft[:d]repeatedL/dtimes, the candidate is"{L/d}{" + enc(t[:d]) + "}".
- Splits: for
- A candidate replaces the current best only if it is strictly shorter. So among equal-length candidates, the earliest one in the order above (raw first) wins.
The encoding of t is the best candidate after all candidates have been examined.
For the empty string, return the empty string.
Constraints
0 <= len(text) <= 150textcontains no digits and no{or}characters (so tokens are unambiguous).- Counts
kmay have several digits, and every digit counts toward the length of the encoding.
Examples
Example 1
Input: shortest_nested_encoding('aaa')
Output: 'aaa'
Example 2
Input: shortest_nested_encoding('ababab')
Output: '3{ab}'
Example 3
Input: shortest_nested_encoding('aabcaabcd')
Output: '2{aabc}d'
Example 4
Input: shortest_nested_encoding('aaaaaaaaaa')
Output: 'a9{a}'
Hints
Hint 1
Think of the answer for each substring as a subproblem: the best encoding of text[i..j] is built from the best encodings of smaller substrings.
Hint 2
For one substring there are three kinds of candidates: leave it raw, cut it into two parts and encode each part, or, if it is a block of identical copies of a shorter unit, wrap the unit's best encoding in a token.
Hint 3
Memoize on the (start, end) pair. Follow the candidate order and the strict-shorter rule from the statement exactly, since that decides ties such as a9{a} versus 10{a}.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Treat every substring text[i..j] as a subproblem and compute its best encoding once, caching it by (i, j).
For a substring there are three kinds of candidates:
- Raw: the substring as it is.
- Split: cut at some position and concatenate the best encodings of the two parts.
- Repeat: if the substring is a shorter unit repeated
counttimes, writecount{...}around the best encoding of that unit. The inner encoding is just another cached subproblem, so nesting needs no extra work.
Candidates are examined in a fixed order: raw first, then splits by increasing left length, then repeats by increasing unit length. A candidate replaces the current best only when it is strictly shorter. This fixes every tie. For ten a characters, the split a + 9{a} is found before the repeat 10{a}, and both have length 5, so the answer is a9{a}.
Why it is correct
An optimal encoding of a substring is one of three things:
- raw text,
- a concatenation of at least two top-level pieces, which is covered by cutting after the first piece (both sides must themselves be optimal, otherwise a shorter replacement exists), or
- a single token
k{p}. Then the substring iskcopies of a unit, and the best innerpis the best encoding of that unit, because all copies are identical.
The DP takes the minimum over a candidate set that always contains an optimal encoding. The fixed order together with the strict-shorter rule picks one deterministic representative among the ties.
Complexity
- There are O(n^2) substrings. Each tries O(n) splits and, for each divisor of its length, one repeat check costing O(n).
- That gives roughly O(n^3) candidate evaluations, plus string concatenation and comparison cost, so up to about O(n^4) character operations in the worst case. This is fine for n up to about 150.
- Space is O(n^2) states, each storing an encoded string of length at most n.
Reference solution
import sys
def shortest_nested_encoding(text: str) -> str:
n = len(text)
if n == 0:
return text
sys.setrecursionlimit(max(10000, n * 10))
memo = {}
def solve(i: int, j: int) -> str:
# Best encoding of text[i..j] (inclusive).
if i > j:
return ""
if i == j:
return text[i]
key = (i, j)
if key in memo:
return memo[key]
best = text[i:j + 1]
length = j - i + 1
# Splits, by increasing left length.
for k in range(i, j):
candidate = solve(i, k) + solve(k + 1, j)
if len(candidate) < len(best):
best = candidate
# Repeats, by increasing unit length.
for unit in range(1, length):
if length % unit != 0:
continue
count = length // unit
pattern = text[i:i + unit]
if text[i:j + 1] == pattern * count:
candidate = f"{count}{{{solve(i, i + unit - 1)}}}"
if len(candidate) < len(best):
best = candidate
memo[key] = best
return best
return solve(0, n - 1)