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 Reverse Calculation Approach INPUT Encoded String s: l e e t 2 c o d e 3 Decoded Tape: "leetleet" (after 2) "leetleetcode" (add code) "leetleetcode" x3 (after 3) Target Index k: k = 10 Letter Digit (repeat) Total decoded length: 36 ALGORITHM STEPS 1 Calculate Total Size Forward pass: compute decoded tape length = 36 2 Reverse Traversal Go backwards through s, adjusting k and size 3 Handle Digits If digit: size /= d, k = k % size 4 Handle Letters If k==0 or k==size, return current letter Reverse Trace: char size k 3 36 10 e 12 10 d 11 10 o 10 10 --> k==size Return 'o'! FINAL RESULT The 10th character is: "o" Position in decoded string: l 1 e 2 e 3 t 4 l 5 e 6 e 7 t 8 c 9 o 10 Output: "o" OK - Found without building full string! Time: O(n) | Space: O(1) Key Insight: Instead of building the entire decoded string (which could be huge), we work backwards! When we hit a digit, the pattern repeats, so k % size gives us the equivalent position. When k == size or k == 0 at a letter, we found our answer. This uses O(1) space! TutorialsPoint - Decoded String at Index | Reverse Calculation Approach
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