class Solution: def decodeAtIndex(self, s: str, k: int) -> str: length = 0 i = 0 # find the length that is less than k while length < k: if s[i].isdigit(): length *= int(s[i]) else: length += 1 i += 1 # Reverse Traversal for j in range(i - 1, -1, -1): char = s[j] if char.isdigit(): # While it's reverse so the total can be devided by it length //= int(char) k %= length else: # When k is used up or k == length return the curr char if k == 0 or k == length: return char length -= 1 # TIP: Reverse Traversal(To avoid create an acutal decoded string) # Reverse: if encountered Letter: len - 1; if encountered Digit: len / 2 # Time Complexity = O(n); Space Complexity = O(1) sol = Solution() print(sol.decodeAtIndex("leet2code3", 10)) print(sol.decodeAtIndex("ha22", 5)) print(sol.decodeAtIndex("a2345678999999999999999", 1)) |