Sign in to devexcode.com with google.com

To continue, google.com will share your name, email address, and profile picture with this site. See this site's privacy policy.

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

Explanation

To solve this problem, we need to simulate the operations that Alice performs on the initial string. We can keep track of the length of the string after each operation and find the k-th character based on the number of operations performed. We can use modulo arithmetic to determine the position of the k-th character in the final string.

Algorithmic Idea

  1. Initialize the string word with "a" and set the current length of the word to 1.
  2. Iterate over the operations array and perform the specified operation.
  3. For operation 0, double the length of the word.
  4. For operation 1, increment each character in the word by one and append the resulting string to the original word.
  5. Calculate the effective length of the word after all operations.
  6. Find the k-th character in the final word using modulo arithmetic.

Time Complexity

The time complexity of this algorithm is O(n), where n is the length of the operations array.

Space Complexity

The space complexity of this algorithm is O(n), where n is the length of the operations array.

class Solution {
    public char findKthCharacter(int k, int[] operations) {
        String word = "a";
        int length = 1;
        
        for (int operation : operations) {
            if (operation == 0) {
                length *= 2;
            } else {
                StringBuilder sb = new StringBuilder();
                for (char ch : word.toCharArray()) {
                    sb.append((char) ((ch - 'a' + 1) % 26 + 'a'));
                }
                word += sb.toString();
            }
        }
        
        int effectiveLength = word.length();
        
        k--; // Convert k to 0-based index
        k %= effectiveLength;
        
        return word.charAt(k);
    }
}

Code Editor (Testing phase)

Improve Your Solution

Use the editor below to refine the provided solution. Select a programming language and try the following:

  • Add import statement if required.
  • Optimize the code for better time or space complexity.
  • Add test cases to validate edge cases and common scenarios.
  • Handle error conditions or invalid inputs gracefully.
  • Experiment with alternative approaches to deepen your understanding.

Click "Run Code" to execute your solution and view the output. If errors occur, check the line numbers and debug accordingly. Resize the editor by dragging its bottom edge.