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

Alice and Bob are playing a string transformation game. Initially, Alice has a string word = "a". You are given a positive integer k.

Bob will ask Alice to perform the following operation repeatedly:

  • Generate a new string by changing each character in word to its next character in the English alphabet
  • Append this new string to the original word

For example:

  • Performing the operation on "c" generates "cd" (c → d, then append)
  • Performing the operation on "zb" generates "zbac" (z → a, b → c, then append)

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

Input & Output

Example 1 — Basic Case
$ Input: k = 5
Output: b
💡 Note: Step 0: "a" → Step 1: "ab" → Step 2: "abbc" → The 5th character (index 4) is 'b'
Example 2 — Small k
$ Input: k = 1
Output: a
💡 Note: The 1st character is always 'a' since we start with "a"
Example 3 — Edge Case
$ Input: k = 4
Output: c
💡 Note: Step 0: "a" → Step 1: "ab" → Step 2: "abbc" → The 4th character is 'c'

Constraints

  • 1 ≤ k ≤ 104

Visualization

Tap to expand
K-th Character in String Game I INPUT Initial String: "a" Target Position: k = 5 String Growth Pattern: a len=1 a b len=2 a b b c len=4 a b b c b c c d len=8 1 2 3 4 5 6 7 8 ALGORITHM STEPS 1 Simulate Growth Build string until length >= k (doubling each time) 2 Operation Rule Each char c becomes c+1 (a-->b, b-->c, z-->a) 3 Track Position k=5 Position 5 is in 2nd half of length-8 string 4 Extract Character Return word[k-1] after sufficient operations Iteration Trace: Op 0: "a" (len=1) Op 1: "a"+"b" (len=2) Op 2: "ab"+"bc" (len=4) Op 3: "abbc"+"bccd" Result: "abbcbccd" (len=8) FINAL RESULT Final String after 3 operations: a b b c b c c d 1 2 3 4 5 6 7 8 k=5 OUTPUT "b" OK - Position 5 = b word[4] = 'b' (0-indexed) 5th character = 'b' Key Insight: Mathematical Pattern Recognition The string length doubles with each operation (1 --> 2 --> 4 --> 8 --> ...). Each new half is the previous string with all characters shifted by 1. For k=5: after 3 operations we have "abbcbccd" with length 8. The 5th position corresponds to the 1st position of the 2nd half (transformed 'a' = 'b'). Time: O(log k), Space: O(2^(log k)) = O(k) TutorialsPoint - Find the K-th Character in String Game I | Mathematical Pattern Recognition
Asked in
Meta 15 Google 12
23.0K Views
Medium Frequency
~15 min Avg. Time
850 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen