Decoded String at Index - 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.
  • If the character read is a digit d, the entire current tape is repeatedly written d - 1 more times in total.

Given an integer k, return the k-th letter (1-indexed) in the decoded string.

Input & Output

Example 1 — Basic Case
$ Input: s = "leet2code3", k = 10
Output: "o"
💡 Note: The decoded string is "leetleetcodeleetleetcodeleetleetcode". The 10th letter is "o".
Example 2 — Simple Multiplication
$ Input: s = "ha22", k = 5
Output: "h"
💡 Note: The decoded string is "hahahaha". The 5th letter is "h".
Example 3 — Single Character
$ Input: s = "a2345678999999999999999", k = 1
Output: "a"
💡 Note: The decoded string starts with "a", so the 1st letter is "a".

Constraints

  • 2 ≤ s.length ≤ 100
  • s consists of lowercase English letters and digits 2-9
  • s starts with a letter
  • 1 ≤ k ≤ 109

Visualization

Tap to expand
Decoded String at Index: Smart vs Brute Forcea2b3inputk = 6Brute Force: aabaababaabbuild entire string❌ Memory overflowfor large stringsproblemSmart Solution:1. Calculate size = 92. Work backwards: k%sizeResult: "b"O(1) spaceO(n) timeInstead of building massive string, use math to find the answer!
Understanding the Visualization
1
Input
Encoded string with letters and digits
2
Decoding Process
Letters add characters, digits repeat the string
3
Smart Solution
Work backwards instead of building full string
Key Takeaway
🎯 Key Insight: Work backwards using modular arithmetic instead of building the exponentially large decoded string
Asked in
Google 45 Amazon 38 Facebook 32 Microsoft 28
125.0K Views
Medium Frequency
~25 min Avg. Time
2.1K 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