I start with the initial string word = "a"
. In each operation, I take the current string and generate a new string by replacing each character with its next character in the English alphabet—where 'z'
wraps around to 'a'
.
Once the length of the string reaches or exceeds k
, I return the k-th character (1-indexed) from the resulting string.
class Solution:
def kthCharacter(self, k: int) -> str:
word = "a"
while len(word) < k:
next_part = ''.join(
chr(((ord(c) - ord('a') + 1) % 26) + ord('a')) for c in word
)
word += next_part
return word[k - 1]
- Time: O(k)
- Space: O(k)
