KatInterview

916. Decoded String at Index

MediumSolutions 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 core challenge of this problem is that the decoded string can be extraordinarily long, far exceeding memory capacity and the limits of standard data types. For instance, a short encoded string like "a234567899..." can result in a string with a length greater than 2^63. Therefore, we cannot simply generate the decoded string and pick the k-th character. This constraint points towards a mathematical or logical approach that works with string lengths rather than the string content itself.

Solution

Decoded String at Index in Python

class Solution:
    def decodeAtIndex(self, s: str, k: int) -> str:
        size = 0
        # First pass: calculate the total length of the decoded string.
        # Python's integers handle arbitrary size, so no overflow issues.
        for char in s:
            if char.isdigit():
                size *= int(char)
            else:
                size += 1

        # Second pass: iterate backwards to find the k-th character.
        for i in range(len(s) - 1, -1, -1):
            char = s[i]
            if char.isdigit():
                size //= int(char)
                # After division, k should be mapped to the remainder
                # in the new, smaller string size.
                k %= size
                # If k becomes 0, it means it was the last character of a block,
                # so it's equivalent to the character at index `size`.
                if k == 0:
                    k = size
            else:
                # If k is at the current end of the string, this character is the answer.
                if k == size:
                    return char
                size -= 1
        
        return "" # Should be unreachable given problem constraints

Decoded String at Index in Java

class Solution {
    public String decodeAtIndex(String s, int k) {
        long size = 0;
        // First pass: calculate the total length of the decoded string.
        for (char c : s.toCharArray()) {
            if (Character.isDigit(c)) {
                size *= (c - '0');
            } else {
                size++;
            }
        }

        long K = k;
        // Second pass: iterate backwards to find the k-th character.
        for (int i = s.length() - 1; i >= 0; i--) {
            char c = s.charAt(i);
            if (Character.isDigit(c)) {
                int d = c - '0';
                size /= d;
                // After division, K should be mapped to the remainder
                // in the new, smaller string size.
                K %= size;
                // If K becomes 0, it means it was the last character of a block,
                // so it's equivalent to the character at index `size`.
                if (K == 0) {
                    K = size;
                }
            } else {
                // If K is at the current end of the string, this character is the answer.
                if (K == size) {
                    return String.valueOf(c);
                }
                size--;
            }
        }

        return null; // Should be unreachable given the problem constraints.
    }
}

Decoded String at Index in C++

class Solution {
public:
    string decodeAtIndex(string s, int k) {
        long long size = 0;
        // First pass: calculate the total length of the decoded string.
        for (char c : s) {
            if (isdigit(c)) {
                size *= (c - '0');
            } else {
                size++;
            }
        }

        long long K = k;
        // Second pass: iterate backwards to find the k-th character.
        for (int i = s.length() - 1; i >= 0; i--) {
            char c = s[i];
            if (isdigit(c)) {
                int d = c - '0';
                size /= d;
                // After division, K should be mapped to the remainder
                // in the new, smaller string size.
                K %= size;
                // If K becomes 0, it means it was the last character of a block,
                // so it's equivalent to the character at index `size`.
                if (K == 0) {
                    K = size;
                }
            } else {
                // If K is at the current end of the string, this character is the answer.
                if (K == size) {
                    return string(1, c);
                }
                size--;
            }
        }

        return ""; // Should be unreachable given the problem constraints.
    }
};

Decoded String at Index in TypeScript

function decodeAtIndex(s: string, k: number): string {
    let size = 0n;

    // First pass: calculate the total length using BigInt for safety.
    for (const char of s) {
        // Constraints guarantee digits are '2'-'9'.
        if (char >= '2' && char <= '9') {
            size *= BigInt(char);
        } else {
            size += 1n;
        }
    }

    let K = BigInt(k);

    // Second pass: iterate backwards to find the k-th character.
    for (let i = s.length - 1; i >= 0; i--) {
        const char = s[i];
        if (char >= '2' && char <= '9') {
            size /= BigInt(char);
            // After division, K should be mapped to the remainder
            // in the new, smaller string size.
            K %= size;
            // If K becomes 0, it means it was the last character of a block,
            // so it's equivalent to the character at index `size`.
            if (K === 0n) {
                K = size;
            }
        } else {
            // If K is at the current end of the string, this character is the answer.
            if (K === size) {
                return char;
            }
            size -= 1n;
        }
    }

    return ""; // Should be unreachable given the problem constraints.
};

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.