KatInterview

471. Encode String with Shortest Length

HardSolutions in Python, Java, C++, TypeScript

Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.

Approach

The problem asks for the shortest possible encoded representation of a given string. The encoding rule is k[encoded_string], where a substring is repeated k times. This problem has optimal substructure and overlapping subproblems, making it a perfect candidate for Dynamic Programming. The core idea is to find the shortest encoding for every possible substring of the input string s.

Solution

Encode String with Shortest Length in Python

class Solution:
    def encode(self, s: str) -> str:
        n = len(s)
        # dp[i][j] stores the shortest encoded string for s[i:j+1]
        dp = [['' for _ in range(n)] for _ in range(n)]

        # Iterate over all possible substring lengths
        for length in range(1, n + 1):
            # Iterate over all possible starting positions
            for i in range(n - length + 1):
                j = i + length - 1
                sub = s[i : j + 1]
                dp[i][j] = sub  # Initialize with the original substring

                # An encoding can only be shorter if the original string length is at least 5
                # e.g., "aaaaa" -> "5[a]" (5 -> 4), "aaaa" -> "4[a]" (4 -> 4)
                if length < 5:
                    continue

                # Case 1: Split the substring into two parts
                for k in range(i, j):
                    left = dp[i][k]
                    right = dp[k + 1][j]
                    if len(left) + len(right) < len(dp[i][j]):
                        dp[i][j] = left + right

                # Case 2: Encode the substring as a repeating pattern
                for p_len in range(1, length // 2 + 1):
                    if length % p_len == 0:
                        repeats = length // p_len
                        pattern = s[i : i + p_len]
                        
                        # Check if `sub` is formed by repeating `pattern`
                        if sub == pattern * repeats:
                            encoded_pattern = dp[i][i + p_len - 1]
                            candidate = str(repeats) + '[' + encoded_pattern + ']'
                            if len(candidate) < len(dp[i][j]):
                                dp[i][j] = candidate

        return dp[0][n - 1]

Encode String with Shortest Length in Java

class Solution {
    public String encode(String s) {
        int n = s.length();
        String[][] dp = new String[n][n];

        // Iterate over all possible substring lengths
        for (int len = 1; len <= n; len++) {
            // Iterate over all possible starting positions
            for (int i = 0; i <= n - len; i++) {
                int j = i + len - 1;
                String sub = s.substring(i, j + 1);
                dp[i][j] = sub; // Initialize with the original substring

                // An encoding can only be shorter if the original string length is at least 5
                // e.g., "aaaaa" -> "5[a]" (5 -> 4), "aaaa" -> "4[a]" (4 -> 4)
                if (len < 5) {
                    continue;
                }

                // Case 1: Split the substring into two parts
                for (int k = i; k < j; k++) {
                    String left = dp[i][k];
                    String right = dp[k + 1][j];
                    if (left.length() + right.length() < dp[i][j].length()) {
                        dp[i][j] = left + right;
                    }
                }

                // Case 2: Encode the substring as a repeating pattern
                for (int p_len = 1; p_len <= len / 2; p_len++) {
                    if (len % p_len == 0) {
                        String pattern = s.substring(i, i + p_len);
                        int repeats = len / p_len;
                        
                        // Check if `sub` is formed by repeating `pattern`
                        if (sub.equals(pattern.repeat(repeats))) {
                            String encodedPattern = dp[i][i + p_len - 1];
                            String candidate = repeats + "[" + encodedPattern + "]";
                            if (candidate.length() < dp[i][j].length()) {
                                dp[i][j] = candidate;
                            }
                        }
                    }
                }
            }
        }

        return dp[0][n - 1];
    }
}

Encode String with Shortest Length in C++

class Solution {
public:
    string encode(string s) {
        int n = s.length();
        vector<vector<string>> dp(n, vector<string>(n, ""));

        // Iterate over all possible substring lengths
        for (int len = 1; len <= n; ++len) {
            // Iterate over all possible starting positions
            for (int i = 0; i <= n - len; ++i) {
                int j = i + len - 1;
                string sub = s.substr(i, len);
                dp[i][j] = sub; // Initialize with the original substring

                // An encoding can only be shorter if the original string length is at least 5
                // e.g., "aaaaa" -> "5[a]" (5 -> 4), "aaaa" -> "4[a]" (4 -> 4)
                if (len < 5) {
                    continue;
                }

                // Case 1: Split the substring into two parts
                for (int k = i; k < j; ++k) {
                    const string& left = dp[i][k];
                    const string& right = dp[k + 1][j];
                    if (left.length() + right.length() < dp[i][j].length()) {
                        dp[i][j] = left + right;
                    }
                }

                // Case 2: Encode the substring as a repeating pattern
                for (int p_len = 1; p_len <= len / 2; ++p_len) {
                    if (len % p_len == 0) {
                        string pattern = s.substr(i, p_len);
                        bool is_repetition = true;
                        for (int start = i + p_len; start <= j; start += p_len) {
                            if (s.substr(start, p_len) != pattern) {
                                is_repetition = false;
                                break;
                            }
                        }

                        if (is_repetition) {
                            int k = len / p_len;
                            string encoded_pattern = dp[i][i + p_len - 1];
                            string candidate = to_string(k) + "[" + encoded_pattern + "]";
                            if (candidate.length() < dp[i][j].length()) {
                                dp[i][j] = candidate;
                            }
                        }
                    }
                }
            }
        }

        return dp[0][n - 1];
    }
};

Encode String with Shortest Length in TypeScript

function encode(s: string): string {
    const n = s.length;
    // dp[i][j] stores the shortest encoded string for s.substring(i, j + 1)
    const dp: string[][] = Array(n).fill(0).map(() => Array(n).fill(''));

    // Iterate over all possible substring lengths
    for (let len = 1; len <= n; len++) {
        // Iterate over all possible starting positions
        for (let i = 0; i <= n - len; i++) {
            const j = i + len - 1;
            const sub = s.substring(i, j + 1);
            dp[i][j] = sub; // Initialize with the original substring

            // An encoding can only be shorter if the original string length is at least 5
            // e.g., "aaaaa" -> "5[a]" (5 -> 4), "aaaa" -> "4[a]" (4 -> 4)
            if (len < 5) {
                continue;
            }

            // Case 1: Split the substring into two parts
            for (let k = i; k < j; k++) {
                const left = dp[i][k];
                const right = dp[k + 1][j];
                if (left.length + right.length < dp[i][j].length) {
                    dp[i][j] = left + right;
                }
            }

            // Case 2: Encode the substring as a repeating pattern
            for (let p_len = 1; p_len <= len / 2; p_len++) {
                if (len % p_len === 0) {
                    const repeats = len / p_len;
                    const pattern = s.substring(i, i + p_len);

                    // Check if `sub` is formed by repeating `pattern`
                    if (sub === pattern.repeat(repeats)) {
                        const encodedPattern = dp[i][i + p_len - 1];
                        const candidate = `${repeats}[${encodedPattern}]`;
                        if (candidate.length < dp[i][j].length) {
                            dp[i][j] = candidate;
                        }
                    }
                }
            }
        }
    }

    return dp[0][n - 1];
};

Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.

LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.