DEV Community

Cover image for 🧙‍♂️Beginner-Friendly Guide "Find the K-th Character in String Game I" – LeetCode 3304 (C++ | Python | JavaScript)
Om Shree
Om Shree

Posted on

🧙‍♂️Beginner-Friendly Guide "Find the K-th Character in String Game I" – LeetCode 3304 (C++ | Python | JavaScript)

Hey adventurers!

In this playful string-based puzzle, we join Alice and Bob in an ever-growing word game. From just a single letter, a mysterious pattern evolves — and you’re tasked with figuring out what the k-th character becomes after repeated transformations. 🌀

Let’s demystify it together.


🧠 Problem Summary

You're given:

  • A game that starts with the string word = "a"
  • A number k, indicating the position of the character you want to retrieve

Each round:

Every character in the current word is changed to its next character in the alphabet, and the result is appended to the word.

Examples:

  • "a" becomes "ab"
  • "ab" becomes "abbc"
  • "abbc" becomes "abbcbccd"

Your goal:

Return the character at position k (1-based index) after enough rounds.


💡 Intuition

If you trace the pattern carefully, you'll realize:

  • The transformation is deterministic.
  • Each new character in the word is one step ahead of its source.
  • The position of each new character follows a binary-like structure — much like the count of 1s in the binary representation of k-1.

Thus, the answer is simply:

'a' + popcount(k - 1)
Enter fullscreen mode Exit fullscreen mode

Where popcount(x) counts the number of 1s in the binary representation of x.


🛠️ C++ Code

class Solution {
 public:
  char kthCharacter(unsigned k) {
    return 'a' + popcount(k - 1);
  }
};
Enter fullscreen mode Exit fullscreen mode

🐍 Python Code

class Solution:
    def kthCharacter(self, k: int) -> str:
        return chr(ord('a') + bin(k - 1).count('1'))
Enter fullscreen mode Exit fullscreen mode

💻 JavaScript Code

var kthCharacter = function(k) {
    const popcount = n => n.toString(2).split('1').length - 1;
    return String.fromCharCode('a'.charCodeAt(0) + popcount(k - 1));
};
Enter fullscreen mode Exit fullscreen mode

📝 Key Insights

  • This elegant transformation can be reduced to analyzing binary patterns.
  • Think of each bit in k-1 as a transformation step.
  • No need to simulate string growth — bitwise logic wins here. 🧠

✅ Final Thoughts

From a simple "a" to a cascade of characters, this problem rewards observation and pattern recognition. It's a neat reminder that clever math can beat brute force.

If you enjoyed this one, share it with a fellow coder! Happy decoding! 💻✨

Top comments (2)

Collapse
 
thedeepseeker profile image
Anna kowoski

this was just one liner, thanks for making this so easy for me.

Collapse
 
om_shree_0709 profile image
Om Shree

Thanks Anna