The Encode String with Shortest Length coding problem asks you to compress a given string into its shortest possible representation. You can encode repeating patterns in the format k[substring], where k is the number of repetitions. For example, "aaaaa" can be encoded as 5[a]. This encoding can be nested, like 2[3[a]2[b]]. The goal is to return any string that has the absolute minimum length after all possible encodings.
This is a "Hard" difficulty problem frequently asked by Google. It tests a candidate's proficiency with dynamic programming interview pattern and their ability to solve optimal substructure problems. It requires exploring all possible ways to split a string and all possible ways to compress it, making it an excellent test of recursive thinking and optimization.
The problem is solved using 2D Dynamic Programming with String Compression.
dp[i][j] as the shortest encoded string for the substring s[i...j].k[s] is at least 4 chars long).k between i and j, and set dp[i][j] = dp[i][k] + dp[k+1][j].s[i...j] itself has a repeating pattern. If s[i...j] can be formed by repeating a smaller string t for count times, check if count[dp_for_t] is shorter than the current dp[i][j].String: "ababababab" (length 10).
"ababab" + "abab". shortest for those might be 3[ab] and 2[ab]. Total: 3[ab]2[ab] (length 10)."ab" repeated 5 times.5[ab] (length 5).dp for the whole string becomes 5[ab]."abcabcabcde" might be encoded as 3[abc]de.Practice the KMP algorithm's "prefix function" or string concatenation tricks ((s + s).find(s, 1)) to find the smallest repeating unit of a string in linear time. This is a vital sub-problem for string compression tasks.