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
String Encoding: Find Shortest RepresentationInput:aabcaabcaabcLength: 12Pattern Detection:aabcaabcaabcPattern "aabc" repeats 3 times!Output:3[aabc]Length: 7 (saved 5 characters!)Benefits:✓ Shorter representation✓ Captures repetition✓ Space efficient
Understanding the Visualization
1
Input
Original string with potential repeating patterns
2
Process
Find repeating substrings and calculate encoding benefits
3
Output
Shortest possible encoding using k[pattern] notation
Key Takeaway
🎯 Key Insight: Dynamic programming helps find optimal encodings by systematically trying all possible pattern combinations and splits.
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