Leetcode #471: Encode String with Shortest Length
In this guide, we solve Leetcode #471 Encode String with Shortest Length in Python and focus on the core idea that makes the solution efficient.
You will see the intuition, the step-by-step method, and a clean Python implementation you can use in interviews.

Problem Statement
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.
Quick Facts
- Difficulty: Hard
- Premium: Yes
- Tags: String, Dynamic Programming
Intuition
The problem breaks into overlapping subproblems, so caching results prevents exponential repetition.
A carefully chosen DP state captures exactly what we need to build the final answer.
Approach
Define the DP state and recurrence, then compute states in the correct order.
Optionally compress space once the recurrence is clear.
Steps:
- Choose a DP state definition.
- Write the recurrence and base cases.
- Compute states in the correct order.
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
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
The time complexity is O(n·m) (typical). The space complexity is O(n·m) or optimized.
Edge Cases and Pitfalls
Watch for boundary values, empty inputs, and duplicate values where applicable. If the problem involves ordering or constraints, confirm the invariant is preserved at every step.
Summary
This Python solution focuses on the essential structure of the problem and keeps the implementation interview-friendly while meeting the constraints.