Decoded String at Index - Problem
Imagine you have a magical decoder tape that processes an encoded string character by character to create a much longer decoded string. Here's how the decoding works:
- When you encounter a letter, write it directly onto the tape
- When you encounter a digit d, repeat the entire current tape content
d-1more times
For example, if the encoded string is "a2bc3":
- Start with:
"" - Read 'a': tape becomes
"a" - Read '2': repeat current tape 1 more time โ
"aa" - Read 'b': tape becomes
"aab" - Read 'c': tape becomes
"aabc" - Read '3': repeat current tape 2 more times โ
"aabcaabcaabc"
Your mission: Given an encoded string s and an integer k, find the k-th character (1-indexed) in the final decoded string without actually building the entire string!
Input & Output
example_1.py โ Basic Case
$
Input:
s = "leet2code3", k = 10
โบ
Output:
"o"
๐ก Note:
The decoded string is "leetleetcodeleetleetcodeleetleetcode" (length 30). The 10th character (1-indexed) is 'o'.
example_2.py โ Simple Multiplication
$
Input:
s = "ha22", k = 5
โบ
Output:
"h"
๐ก Note:
Decoding: 'h' โ 'ha' โ 'haha' โ 'hahahahahahahaha'. The 5th character is 'h'.
example_3.py โ Single Character
$
Input:
s = "a2345678999999999999999", k = 1
โบ
Output:
"a"
๐ก Note:
Even though the final string would be astronomically long, the first character is always 'a'.
Constraints
- 2 โค s.length โค 100
- s consists only of lowercase English letters and digits 2 through 9
- s starts with a letter
- 1 โค k โค 109
- It is guaranteed that k is less than or equal to the length of the decoded string
- Important: The decoded string can be extremely long (exponential growth), but k is guaranteed to be valid
Visualization
Tap to expand
Understanding the Visualization
1
Calculate Final Size
First pass determines how long the decoded string would be
2
Reverse the Process
Work backwards, undoing multiplications step by step
3
Use Modulo Magic
k % current_size tells us which section contains our target
4
Find the Character
When k becomes 0 and we hit a letter, we found our answer!
Key Takeaway
๐ฏ Key Insight: Instead of expanding forward (which uses exponential space), we shrink backward using modulo arithmetic to mathematically determine which original character maps to position k.
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code