Encode String with Shortest Length

Hard

Topics
StringDynamic Programming

Given a string s, encode it so that its encoded length is as short as possible. The encoding rule is k[encoded_string], where encoded_string is repeated exactly k times. If encoding does not make the string shorter, keep it as-is. When several encodings share the minimum length, return the lexicographically smallest one.

Example 1

a0a1a2
Input:  s = "aaa"
Output: "aaa"

Example 2

a0a1a2a3a4
Input:  s = "aaaaa"
Output: "5[a]"

Example 3

a0a1a2a3a4a5a6a7a8a9
Input:  s = "aaaaaaaaaa"
Output: "10[a]"

Constraints

  • 1 <= s.length <= 12
  • s consists of lowercase English letters only.
Editorial — intuition, approach, complexity and pitfalls

Intuition

Every encoding of a string is built from two moves: concatenate two encoded pieces, or wrap a repeated unit as k[unit]. Both are decisions about intervals, so the shortest encoding of each interval can be built from shorter ones — interval DP.

For an interval, consider three candidates: the raw text, every way to split it into two parts using their already-computed encodings, and — if the text is periodic — k[encoding of the period]. Note it is the encoding of the period, not the raw period, so nested compression comes out for free.

Periodicity is detected with the concatenation trick: (sub+sub).find(sub, 1) returns the smallest shift that maps the string onto itself, and that shift is the period length when it is less than the string's length.

Approach

  1. Fill dp by increasing interval length.
  2. Start each interval's best as its raw text.
  3. Try every split point, comparing dp[i][k] + dp[k+1][j].
  4. Find the period with (sub+sub).find(sub, 1); if it is shorter than the text, try str(times) + '[' + dp of the period + ']'.
  5. Break length ties by taking the lexicographically smaller string.

Dry Run

s = "aabcaabcd"

period detection
  "aabcaabc"  shift 4 of 8   periodic, period "aabc" repeated twice
  "abab"      shift 2 of 4   periodic
  "abc"       shift 3 of 3   not periodic

interval results
  "a"          -> "a"
  "aa"         -> "aa"          2[a] is also 4 chars, raw wins the tie
  "aabc"       -> "aabc"
  "aabcaabc"   -> "2[aabc]"     7 chars beats 8
  "aabcaabcd"  -> "2[aabc]d"    8 chars beats 9

answer "2[aabc]d"

  "aaaaaaaaaaaa" -> "12[a]"   5 chars beats 12

Complexity

  • Time — O(n³): O(n²) intervals, each trying O(n) splits. The period check is an extra O(n) per interval, which is absorbed.
  • Space — O(n²) table entries, each holding a string of up to O(n) characters, so O(n³) characters in total. At the stated bound of 12 this is trivial; the honest number is worth stating anyway.

Common Pitfalls

  • Wrapping the raw period instead of its encoding. dp of the period may itself be compressed, and skipping that loses every nested encoding.
  • Using only the shortest period. The shown code does, and it is correct — any longer repeating unit is itself a repetition of the shortest one, so it can never produce a shorter encoding. Worth justifying rather than assuming.
  • Forgetting that the encoding may be no shorter than the input, in which case the raw text wins. Seeding each interval's best with the raw substring handles it.
  • Ignoring the lexicographic tie-break when several encodings share the minimum length. The problem asks for the smallest, so the comparison must be on length first and content second.
  • Counting the digits of k as one character. At 12 characters k can reach 12, so str(times) can be two characters and the length arithmetic must use the actual string.
  • Greedily compressing the longest repeated block first. Local compression can block a better global split, which is exactly why this is a DP.

Full Solution — all languages

class Solution:
    def encode(self, s):
        n = len(s)
        if n == 0:
            return ""
        def better(a, b):
            if len(a) != len(b):
                return a if len(a) < len(b) else b
            return a if a <= b else b
        dp = [[None] * n for _ in range(n)]
        for length in range(1, n + 1):
            for i in range(0, n - length + 1):
                j = i + length - 1
                sub = s[i:j + 1]
                best = sub
                for k in range(i, j):
                    best = better(best, dp[i][k] + dp[k + 1][j])
                rep = (sub + sub).find(sub, 1)
                if rep < len(sub):
                    unit_len = rep
                    times = len(sub) // unit_len
                    best = better(best, str(times) + '[' + dp[i][i + unit_len - 1] + ']')
                dp[i][j] = best
        return dp[0][n - 1]
SensAI
Beta
Tap the mic to stop voice mode