3307: Find-the-K-th-Character-in-String-Game-II
Hard


table of contents

The intuition is, to have constraints as large as 1 <= k <= 10^14, there has to be some pattern that exists allowing us to retrieve the kth character quickly.

You can see this come up in the example listed below, where you have input:

After 4 operations, we have this:

a|b|a|b|b|c|b|c|a|b| a| b| b| c| b| c
0|1|2|3|4|5|6|7|8|9|10|11|12|13|14|15

where the numbers below denote the letters respective index.

While looking at the letters and their respective index, a pattern begins to reveal itself. Take index 11 as an example:

a|b|a|*b*|b|c|b|c -> a|b| a|* b*| b| c| b| c
0|1|2|*3*|4|5|6|7 -> 8|9|10|*11*|12|13|14|15
a|*b* -> a|*b*
0|*1* -> 2|*3*
*a* -> *b* 
*0* -> *1* 

If we write 11 into binary, 0b1011, and relate the position of each 1 to an operation, for example:

TLDR:

After n operations, word will be of length 2^n. We know that the:

Given their respective indices:

Using an inductive proof, we can show that the nth bit being set to 1 means that the respective operation has been done on the kth character.

code

class Solution {
public:
    char kthCharacter(long long k, vector<int>& operations) {
        char ans = 'a';
        int index = 0;
        k -= 1;
        while (k > 0) {
            if (k % 2 == 1 && operations[index] == 1) {
                if (ans-'a' == 25) {
                    ans = 'a';
                } else {
                    ans = ans+1;
                }
            }
            index = (index + 1) % operations.size();
            k >>= 1;
        }
        return ans;
    }
};

complexity

time taken