Encode String with Shortest Length — LeetCode 471 Python Solution

HardLeetCode PremiumStringDynamic Programming
Problem
#471
Reading time
4 min

The problem

Given a string s, encode the string such that its encoded length is the shortest. The encoding rule is: k[encoded_string], where the encoded_string inside the square brackets is being repeated exactly k times.

Example

Input
s = "aaa"
Output
"aaa"
Explanation
There is no way to encode it such that it is shorter than the input string, so we do not encode it.

Python solution

Python
class Solution:
    def encode(self, s: str) -> str:
        def g(i: int, j: int) -> str:
            t = s[i : j + 1]
            if len(t) < 5:
                return t
            k = (t + t).index(t, 1)
            if k < len(t):
                cnt = len(t) // k
                return f"{cnt}[{f[i][i + k - 1]}]"
            return t

        n = len(s)
        f = [[None] * n for _ in range(n)]
        for i in range(n - 1, -1, -1):
            for j in range(i, n):
                f[i][j] = g(i, j)
                if j - i + 1 > 4:
                    for k in range(i, j):
                        t = f[i][k] + f[k + 1][j]
                        if len(f[i][j]) > len(t):
                            f[i][j] = t
        return f[0][-1]

Complexity

MeasureComplexity
TimeO(n·m) (typical)
SpaceO(n·m) or optimized auxiliary

Pattern: Dynamic Programming

Define a state, write the transition, and stop recomputing the same subproblem. LeetCode 471. Encode String with Shortest Length is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Dynamic Programming.

The dynamic programming guide has the Python template for the pattern and the 481 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 471. Encode String with Shortest Length?
LeetCode 471. Encode String with Shortest Length is rated Hard on LeetCode.
What topics does LeetCode 471. Encode String with Shortest Length cover?
LeetCode 471. Encode String with Shortest Length is tagged String and Dynamic Programming on LeetCode.
Is LeetCode 471. Encode String with Shortest Length a premium problem?
Yes. LeetCode 471. Encode String with Shortest Length is a LeetCode Premium problem, so the full statement and test cases require a paid LeetCode subscription.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview