Skip to content

3600. Find The K Th Character In String Game I

Difficulty: Easy

LeetCode Problem View on GitHub


3600. Find the K-th Character in String Game I

Easy


Alice and Bob are playing a game. Initially, Alice has a string word = "a".

You are given a positive integer k.

Now Bob will ask Alice to perform the following operation forever:

  • 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".

Return the value of the kth character in word, after enough operations have been done for word to have at least k characters.

Note that the character 'z' can be changed to 'a' in the operation.

 

Example 1:

Input: k = 5

Output: "b"

Explanation:

Initially, word = "a". We need to do the operation three times:

  • Generated string is "b", word becomes "ab".
  • Generated string is "bc", word becomes "abbc".
  • Generated string is "bccd", word becomes "abbcbccd".

Example 2:

Input: k = 10

Output: "c"

 

Constraints:

  • 1 <= k <= 500

Solution

class Solution {
    public char kthCharacter(int k) {
        StringBuilder current = new StringBuilder();
        current.append("a");
        while (true) {
            if (current.length() >= k)
                break;
            StringBuilder newString = new StringBuilder();
            String tempCurrent = current.toString();
            for (int i = 0; i < tempCurrent.length(); i++) {
                char c = tempCurrent.charAt(i);
                if (c == 'z')
                    newString.append('a');
                else
                    newString.append((char)(c + 1));
            }
            current.append(newString);
        }
        return current.toString().charAt(k - 1);
    }
}

Complexity Analysis

  • Time Complexity: O(?)
  • Space Complexity: O(?)

Approach

Detailed explanation of the approach will be added here