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-1 more times

For example, if the encoded string is "a2bc3":

  1. Start with: ""
  2. Read 'a': tape becomes "a"
  3. Read '2': repeat current tape 1 more time โ†’ "aa"
  4. Read 'b': tape becomes "aab"
  5. Read 'c': tape becomes "aabc"
  6. 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
Decoded String at Index - Visual SolutionExample: s = "a2bc3", k = 5Forward Process (conceptual):"a" โ†’ "aa" โ†’ "aab" โ†’ "aabc" โ†’ "aabcaabcaabc" (length 12)Reverse Process (actual algorithm):3size=12k=5%12=5csize=4k=5%4=1bsize=3k=1%3=12size=2k=1%2=1asize=1k=1%1=0k=0! Found it!Answer: 'a' - No string building required!
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.
Asked in
Google 45 Amazon 32 Meta 28 Apple 15
89.2K Views
Medium Frequency
~15 min Avg. Time
1.8K Likes
Ln 1, Col 1
Smart Actions
๐Ÿ’ก Explanation
AI Ready
๐Ÿ’ก Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen