Ctrl K

Shortest Repeat Encoding

Hard
A string can be compressed with the notation m[x], meaning the string x repeated m times in a row (m is an integer ≥ 2, and x may itself be compressed). For example, 3[ab] stands for ababab and 2[2[ab]c] for ababcababc. Compressed and plain pieces can be chained: a3[b] is abbb. You get a string text. Return its shortest encoding. To make the answer unique, the encoding is built recursively by these rules (a function enc(t) for a string t): 1. If len(t) < 5, then enc(t) = t. 2. Otherwise the default candidate is t itself. If t consists entirely of m ≥ 2 copies of a shorter block, take the shortest such block p; the candidate becomes m[enc(p)]. 3. Then try every split t = left + right, from left to right; enc(left) + enc(right) replaces the candidate only when it is **strictly shorter** than the current candidate. Return enc(text).
Example 1
text="cccccc" → '6[c]'

Six cs in a row: 6[c] takes 4 characters instead of 6.

Example 2
text="xyzxyzxyzq" → '3[xyz]q'

The whole string is not a repetition. The best cut is after the ninth letter: 3[xyz] plus q, 7 characters in total.

Example 3
text="abab" → 'abab'

Strings shorter than 5 characters stay as they are.

Constraints
  • 1 ≤ len(text) ≤ 150
  • text consists of lowercase English letters
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsPattern With Dot and Star HardLongest Balanced Bracket Stretch HardDoes the Text Fit the Pattern HardShuffle by Cutting and Swapping HardWays to Cross Out Hard
loading Python…
Input
text="cccccc"
Expected
'6[c]'

Run checks the first 3 tests in your browser. Submit checks all 93 tests on the server, hidden ones included.