Encode String with Shortest Length
Hard
Topics
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
Input: s = "aaa" Output: "aaa"
Example 2
Input: s = "aaaaa" Output: "5[a]"
Example 3
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
- Fill
dpby increasing interval length. - Start each interval's best as its raw text.
- Try every split point, comparing
dp[i][k] + dp[k+1][j]. - Find the period with
(sub+sub).find(sub, 1); if it is shorter than the text, trystr(times) + '[' + dp of the period + ']'. - 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 12Complexity
- 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.
dpof 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
kas one character. At 12 characterskcan reach 12, sostr(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]import java.util.*;
class Solution {
public String encode(String s) {
int n = s.length();
if (n == 0) return "";
String[][] dp = new String[n][n];
for (int len = 1; len <= n; len++) {
for (int i = 0; i + len - 1 < n; i++) {
int j = i + len - 1;
String sub = s.substring(i, j + 1);
String best = sub;
for (int k = i; k < j; k++) best = better(best, dp[i][k] + dp[k + 1][j]);
String dbl = sub + sub;
int rep = dbl.indexOf(sub, 1);
if (rep < sub.length()) {
int unitLen = rep, times = sub.length() / unitLen;
best = better(best, times + "[" + dp[i][i + unitLen - 1] + "]");
}
dp[i][j] = best;
}
}
return dp[0][n - 1];
}
private String better(String a, String b) {
if (a.length() != b.length()) return a.length() < b.length() ? a : b;
return a.compareTo(b) <= 0 ? a : b;
}
}#include <bits/stdc++.h>
using namespace std;
class Solution {
public: string encode(string s) {
int n = s.size();
if (n == 0) return "";
auto better = [](const string& a, const string& b) -> string {
if (a.size() != b.size()) return a.size() < b.size() ? a : b;
return a <= b ? a : b;
};
vector<vector<string>> dp(n, vector<string>(n));
for (int len = 1; len <= n; len++) {
for (int i = 0; i + len - 1 < n; i++) {
int j = i + len - 1;
string sub = s.substr(i, len);
string best = sub;
for (int k = i; k < j; k++) best = better(best, dp[i][k] + dp[k + 1][j]);
string dbl = sub + sub;
int rep = (int) dbl.find(sub, 1);
if (rep < (int)sub.size()) {
int unitLen = rep, times = sub.size() / unitLen;
best = better(best, to_string(times) + "[" + dp[i][i + unitLen - 1] + "]");
}
dp[i][j] = best;
}
}
return dp[0][n - 1];
}
};/**
* @param {string} s
* @return {string}
*/ var encode = function(s) {
const n = s.length;
if (n === 0) return "";
const better = (a, b) => {
if (a.length !== b.length) return a.length < b.length ? a : b;
return a <= b ? a : b;
};
const dp = Array.from({length: n}, () => new Array(n));
for (let len = 1; len <= n; len++) {
for (let i = 0; i + len - 1 < n; i++) {
const j = i + len - 1, sub = s.substring(i, j + 1);
let best = sub;
for (let k = i; k < j; k++) best = better(best, dp[i][k] + dp[k + 1][j]);
const rep = (sub + sub).indexOf(sub, 1);
if (rep < sub.length) {
const unitLen = rep, times = sub.length / unitLen;
best = better(best, times + '[' + dp[i][i + unitLen - 1] + ']');
}
dp[i][j] = best;
}
}
return dp[0][n - 1];
};