Find the K-th Character in String Game I Problem
#3304
Try it yourself first
Five languages, sample and hidden tests, right in the browser.
Practice it as an interview
Talk through your solution with an AI interviewer while you code.
Description
LeetCode Problem 3304.
Alice and Bob are playing a game. Initially, Alice has a string word = "a".
You are given a positive integer k.
Now Bob will ask Alice to perform the following operation forever:
- Generate a new string by changing each character in
wordto its next character in the English alphabet, and append it to the originalword.
For example, performing the operation on "c" generates "cd" and performing the operation on "zb" generates "zbac".
Return the value of the k^th character in word, after enough operations have been done for word to have at least k characters.
Example 1:
Input: k = 5
Output: "b"
Explanation:
Initially, word = "a". We need to do the operation three times:
- Generated string is "b", word becomes "ab".
- Generated string is "bc", word becomes "abbc".
- Generated string is "bccd", word becomes "abbcbccd".
Example 2:
Input: k = 10
Output: "c"
Constraints:
1 <= k <= 500
Solution
Approach: Simulation
Keep the word as an array of letter offsets. While it has fewer than k characters, append a copy of it with every offset increased by one (modulo 26). Then return the letter at position k - 1.
Complexity: O(k) time and O(k) space.
class Solution:
def kthCharacter(self, k: int) -> str:
word = [0]
while len(word) < k:
word.extend([(x + 1) % 26 for x in word])
return chr(ord("a") + word[k - 1])