Encode String with Shortest Length - 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. Note that k should be a positive integer.

If an encoding process does not make the string shorter, then do not encode it.

If there are several solutions, return any of them.

Input & Output

Example 1 — Repeating Pattern
$ Input: s = "aaa"
Output: "aaa"
💡 Note: Since "aaa" has length 3, and encoding "3[a]" has length 4, we don't encode it. Return the original string.
Example 2 — Multiple Repeats
$ Input: s = "aabaaba"
Output: "2[aab]a"
💡 Note: The pattern "aab" repeats 2 times, plus one extra 'a'. So "2[aab]a" (length 7) is shorter than original (length 7). Actually they're equal, but we can choose to encode.
Example 3 — No Benefit
$ Input: s = "abcd"
Output: "abcd"
💡 Note: No repeating patterns exist, and the string is short enough that encoding wouldn't help. Return original.

Constraints

  • 1 ≤ s.length ≤ 150
  • s consists of only lowercase English letters

Visualization

Tap to expand
Encode String with Shortest Length INPUT Input String s: 'a' 'a' 'a' 0 1 2 String Value: s = "aaa" Length: 3 characters All same character 'a' Encoding Format: k[encoded_string] k = repeat count ALGORITHM STEPS 1 Check Encoding Possible: 3[a] 2 Compare Lengths Original: len("aaa") = 3 Encoded: len("3[a]") = 4 3 Evaluate 3 < 4 (original shorter) 4 Decision Keep original string (encoding not shorter) Form Length "aaa" 3 "3[a]" 4 FINAL RESULT Output String: 'a' 'a' 'a' Return Value: "aaa" Status: OK No encoding applied Original string is already the shortest form Length: 3 characters Key Insight: Encoding k[s] adds overhead: the number k, brackets '[' and ']'. For short strings like "aaa" (length 3), the encoded form "3[a]" (length 4) is actually LONGER. Only encode when the result is strictly shorter. Dynamic Programming is used for longer strings to find optimal substring encodings. TutorialsPoint - Encode String with Shortest Length | Optimal Solution
Asked in
Google 12 Facebook 8 Amazon 6
15.4K Views
Medium Frequency
~35 min Avg. Time
645 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen