Leetcode #880: Decoded String at Index
In this guide, we solve Leetcode #880 Decoded String at Index in Python and focus on the core idea that makes the solution efficient.
You will see the intuition, the step-by-step method, and a clean Python implementation you can use in interviews.

Problem Statement
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.
Quick Facts
- Difficulty: Medium
- Premium: No
- Tags: Stack, String
Intuition
The problem has a natural nested or last-in-first-out structure.
A stack lets us resolve matches in the correct order as we scan.
Approach
Push items as they appear and pop when you can finalize a decision.
The stack captures the unresolved part of the input.
Steps:
- Push elements as you scan.
- Pop when a rule or match is satisfied.
- Use the stack to compute results.
Example
Input: s = "leet2code3", k = 10
Output: "o"
Explanation: The decoded string is "leetleetcodeleetleetcodeleetleetcode".
The 10th letter in the string is "o".
Python Solution
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
The time complexity is , where is the length of the string. The space complexity is .
Edge Cases and Pitfalls
Watch for boundary values, empty inputs, and duplicate values where applicable. If the problem involves ordering or constraints, confirm the invariant is preserved at every step.
Summary
This Python solution focuses on the essential structure of the problem and keeps the implementation interview-friendly while meeting the constraints.