Decoded String at Index — LeetCode 880 Python Solution
- Problem
- #880
- Pattern
- Stack
- Reading time
- 3 min
- Source
- leetcode.com
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
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 -= 1Complexity
| Measure | Complexity |
|---|---|
| Time | O(n), where n is the length of the string |
| Space | O(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.