You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
// 3307. Find the K-th Character in String Game II
2
+
// Alice and Bob are playing a game. Initially, Alice has a string word = "a".
3
+
// 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.
4
+
// Now Bob will ask Alice to perform all operations in sequence:
5
+
// If operations[i] == 0, append a copy of word to itself.
6
+
// 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 original word. For example, performing the operation on "c" generates "cd" and performing the operation on "zb" generates "zbac".
7
+
// Return the value of the kth character in word after performing all the operations.
8
+
// Note that the character 'z' can be changed to 'a' in the second type of operation.
9
+
10
+
11
+
// Solution: Math
12
+
13
+
// Trace backwards.
14
+
// Starting from the kth index, trace backwards through the operations and undo them one-by-one.
15
+
// Eventually, we will find ourselves at the starting position.
16
+
17
+
// When operations[i] === 1, we want to add to a count that keeps track of the offset we need to add to the initial "a".
18
+
// If operations[i] === 0, just jump to the equivalent index in the first half of the current string.
19
+
20
+
// e.g. operations = [1,1,0,1]
21
+
// word = "a|b|bc|abbc|bccdbccd"
22
+
// 0 1 23 4567 89012345
23
+
// Depending on the current position (starting from k-1),
24
+
// we need to find the current operation index.
25
+
// Observe the example above,
26
+
// operation index -> current index in word
27
+
// _ -> 0
28
+
// 0 -> 1
29
+
// 1 -> 2,3
30
+
// 2 -> 4,5,6,7
31
+
// 3 -> 8,9,10,11,12,13,14,15
32
+
// Formula to find the operation index: floor(log2(i)).
33
+
// To find the equivalent index after (or rather before) the operation, formula is: i - 2^operation index.
0 commit comments