LeetCode-in-Java

3307. Find the K-th Character in String Game II

Hard

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:

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.

Example 1:

Input: k = 5, operations = [0,0,0]

Output: “a”

Explanation:

Initially, word == "a". Alice performs the three operations as follows:

Example 2:

Input: k = 10, operations = [0,1,0,1]

Output: “b”

Explanation:

Initially, word == "a". Alice performs the four operations as follows:

Constraints:

Solution

public class Solution {
    public char kthCharacter(long k, int[] operations) {
        if (k == 1) {
            return 'a';
        }
        long len = 1;
        long newK = -1;
        int operation = -1;
        for (int ope : operations) {
            len *= 2;
            if (len >= k) {
                operation = ope;
                newK = k - len / 2;
                break;
            }
        }
        char ch = kthCharacter(newK, operations);
        if (operation == 0) {
            return ch;
        }
        return ch == 'z' ? 'a' : (char) (ch + 1);
    }
}