Skip to main content
LeetCode 471, Hard. Topics: String, Dynamic Programming. View on LeetCode. Generate this problem as a practice environment: tested reference solution, 12 parametrized pytest cases, and a playground notebook:

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. 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.

Examples

Constraints

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

Solution

Reference implementation from solution.py on GitHub, full suite in test_solution.py:

Complexity

Tags

NeetCode All.
Last modified on September 7, 2026