Decoded String at Index — LeetCode 880 Python Solution

MediumStackString
Problem
#880
Pattern
Stack
Reading time
3 min

The problem

You are given an encoded string s. To decode the string to a tape, the encoded string is read one character at a time and the following steps are taken: If the character read is a letter, that letter is written onto the tape.

Example

Input
s = "leet2code3", k = 10
Output
"o"
Explanation
The decoded string is "leetleetcodeleetleetcodeleetleetcode".

Python solution

Python
class Solution:
    def decodeAtIndex(self, s: str, k: int) -> str:
        m = 0
        for c in s:
            if c.isdigit():
                m *= int(c)
            else:
                m += 1
        for c in s[::-1]:
            k %= m
            if k == 0 and c.isalpha():
                return c
            if c.isdigit():
                m //= int(c)
            else:
                m -= 1

Complexity

MeasureComplexity
TimeO(n), where n is the length of the string
SpaceO(1) auxiliary

Pattern: Stack

When the most recent unresolved thing is the one that matters, use a stack. LeetCode 880. Decoded String at Index is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Stack.

The stack guide has the Python template for the pattern and the 194 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 880. Decoded String at Index?
LeetCode 880. Decoded String at Index is rated Medium on LeetCode.
What is the time complexity of LeetCode 880. Decoded String at Index?
The Python solution on this page runs in O(n), where n is the length of the string.
What is the space complexity of LeetCode 880. Decoded String at Index?
The Python solution on this page uses O(1) auxiliary space.
What topics does LeetCode 880. Decoded String at Index cover?
LeetCode 880. Decoded String at Index is tagged Stack and String on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview