Decoded String at Index : Array + math

Input: S = "leet2code3", K = 10
Output: "o"
Explanation:
The decoded string is "leetleetcodeleetleetcodeleetleetcode".
The 10th letter in the string is "o".
Input: S = "ha22", K = 5
Output: "h"
Explanation:
The decoded string is "hahahaha". The 5th letter is "h".
Input: S = "a2345678999999999999999", K = 1
Output: "a"
Explanation:
The decoded string is "a" repeated 8301530446056247680 times. The 1st letter is "a".

Intuition :Work Backwards

class Solution:
def decodeAtIndex(self, S: str, K: int) -> str:
size = 0
# Find size = length of decoded string
for c in S:
if c.isdigit():
size *= int(c)
else:
size += 1
# print(size)
# print(K)
# print("*****")
for c in reversed(S):

K %= size
# print(K, size)
if K == 0 and c.isalpha():
return c
if c.isdigit():
size /= int(c)
else:
size -= 1
"leet2code3"
10
36
10
*****
*****
10 36
*****
10.0 12.0
*****
10.0 11.0
*****
0.0 10.0
"o"

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store