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 ith operation.
Now Bob will ask Alice to perform all operations in sequence:
If operations[i] == 0, append a copy of word to itself.
If operations[i] == 1, generate a new string by changing each character in word to 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 kth character in word after performing all the operations.
Note that the character 'z' can be changed to 'a' in the second type of operation.
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"`.
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"`.
Instead of building the string (which is infeasible for large k), we track the length of the string after each operation. We then work backwards, simulating the operations in reverse to find the k-th character, reducing k as we go.
classSolution {
funkthCharacter(k: Long, operations: IntArray): Char {
var ch = 'a'val lens = LongArray(operations.size + 1)
lens[0] = 1for (i in operations.indices) {
val temp = 2 * lens[i]
lens[i+1] = if (temp > k) k else temp
}
var kk = k
for (i in operations.size - 1 downTo 0) {
if (kk > lens[i]) {
kk -= lens[i]
if (operations[i] ==1) {
ch = if (ch =='z') 'a'else ch + 1 }
}
}
return ch
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
classSolution:
defkthCharacter(self, k: int, operations: list[int]) -> str:
ch ='a' lens = [1]
for op in operations:
temp =2* lens[-1]
lens.append(k if temp > k else temp)
for i in range(len(operations) -1, -1, -1):
if k > lens[i]:
k -= lens[i]
if operations[i] ==1:
ch = chr((ord(ch) - ord('a') +1) %26+ ord('a'))
return ch