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:
2
and 9
), the entire current tape is repeatedly written d
-1 more times, where d
is the digit.Given an integer k
, return the k
-th letter (1-indexed) in the decoded string.
Example:
Input: s = "leet2code3", k = 10
Output: "o"
Input: s = "ha22", k = 5
Output: "h"
Constraints:
2 <= s.length <= 100
1 <= k <= 10^9
s
contains only lowercase English letters and digits 2
through 9
.k
is less than or equal to the length of the decoded string.s
will be well-formed without any invalid characters?2
through 9
?k
be larger than the length of the string s
?size
of the ‘decoded’ part accordingly.k
as decoding progresses backward.def decodeAtIndex(s: str, k: int) -> str:
size = 0
# Find size of the decoded string
for c in s:
if c.isdigit():
size *= int(c)
else:
size += 1
for c in reversed(s):
k %= size
if k == 0 and c.isalpha():
return c
if c.isdigit():
size //= int(c)
else:
size -= 1
# Example usage
print(decodeAtIndex("leet2code3", 10)) # Output: "o"
print(decodeAtIndex("ha22", 5)) # Output: "h"
size
to 0: This keeps track of the size of the decoded string.s
and update size
. For digits, multiply size
by the digit value.size
by one.k
using modular arithmetic (k % size
), shrink the problem size.size
backward for both digits and letters.k == 0
for a letter, it means the current letter is the result.The time complexity is (O(n)), where (n) is the length of the string s
, since we’re traversing the string a couple of times. This is efficient given the constraints.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?