3304. Find the K-th Character in String Game I LeetCode Solution

In this guide, you will get 3304. Find the K-th Character in String Game I LeetCode Solution with the best time and space complexity. The solution to Find the K-th Character in String Game I problem is provided in various programming languages like C++, Java, and Python. This will be helpful for you if you are preparing for placements, hackathons, interviews, or practice purposes. The solutions provided here are very easy to follow and include detailed explanations.

Table of Contents

  1. Problem Statement
  2. Complexity Analysis
  3. Find the K-th Character in String Game I solution in C++
  4. Find the K-th Character in String Game I solution in Java
  5. Find the K-th Character in String Game I solution in Python
  6. Additional Resources
3304. Find the K-th Character in String Game I LeetCode Solution image

Problem Statement of Find the K-th Character in String Game I

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”.

See also  219. Contains Duplicate II LeetCode Solution

Example 2:

Input: k = 10
Output: “c”

Constraints:

1 <= k <= 500

Complexity Analysis

  • Time Complexity: O(\log k)
  • Space Complexity: O(1)

3304. Find the K-th Character in String Game I LeetCode Solution in C++

class Solution {
 public:
  char kthCharacter(unsigned k) {
    return 'a' + popcount(k - 1);
  }
};
/* code provided by PROGIEZ */

3304. Find the K-th Character in String Game I LeetCode Solution in Java

class Solution {
  public char kthCharacter(int k) {
    return (char) ('a' + Integer.bitCount(k - 1));
  }
}
// code provided by PROGIEZ

3304. Find the K-th Character in String Game I LeetCode Solution in Python

class Solution:
  def kthCharacter(self, k: int) -> str:
    return string.ascii_lowercase[(k - 1).bit_count()]
# code by PROGIEZ

Additional Resources

Happy Coding! Keep following PROGIEZ for more updates and solutions.