Find the K-th Character in String Game II Problem
Description
LeetCode Problem 3307.
Alice and Bob are playing a game. Initially, Alice has a string word = "a".
You are given a positive integer k. You are also given an integer array operations, where operations[i] represents the type of the i^th operation.
Now Bob will ask Alice to perform all operations in sequence:
- If
operations[i] == 0, append a copy ofwordto itself. - If
operations[i] == 1, generate a new string by changing each character inwordto 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 performing all the operations.
Note that the character 'z' can be changed to 'a' in the second type of operation.
Example 1:
Input: k = 5, operations = [0,0,0]
Output: "a"
Explanation:
Initially, word == "a". Alice performs the three operations as follows:
- Appends "a" to "a", word becomes "aa".
- Appends "aa" to "aa", word becomes "aaaa".
- Appends "aaaa" to "aaaa", word becomes "aaaaaaaa".
Example 2:
Input: k = 10, operations = [0,1,0,1]
Output: "b"
Explanation:
Initially, word == "a". Alice performs the four operations as follows:
- Appends "a" to "a", word becomes "aa".
- Appends "bb" to "aa", word becomes "aabb".
- Appends "aabb" to "aabb", word becomes "aabbaabb".
- Appends "bbccbbcc" to "aabbaabb", word becomes "aabbaabbbbccbbcc".
Constraints:
1 <= k <= 10^141 <= operations.length <= 100operations[i]is either 0 or 1.- The input is generated such that
wordhas at leastkcharacters after all operations.
Solution
Approach: Walk Back Through the Operations
Each operation doubles the word, so after i operations its length is 2^i. Find the first length n = 2^i that is at least k; only the first i operations matter.
Now undo the operations from the last one to the first. If k is in the second half (k > n / 2), that character is a copy of position k - n / 2 in the first half, shifted by one letter when operations[i - 1] is 1; add that shift to a counter d and replace k by k - n / 2. If k is in the first half, the operation does not change it. Then halve n and continue until n = 1.
The answer is the letter d mod 26 steps after 'a'.
Complexity: O(log k) time and O(1) space.
class Solution:
def kthCharacter(self, k: int, operations: List[int]) -> str:
n, i = 1, 0
while n < k:
n *= 2
i += 1
d = 0
while n > 1:
if k > n // 2:
k -= n // 2
d += operations[i - 1]
n //= 2
i -= 1
return chr(d % 26 + ord("a"))