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

Alice and Bob are playing a game. Initially, Alice has a string word = "a". You are given a positive integer k and an integer array operations, where operations[i] represents the type of the i-th operation.

Now Bob will ask Alice to perform all operations in sequence:

  • If operations[i] == 0, append a copy of word to itself.
  • If operations[i] == 1, 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 operation 1 on "c" generates "cd" and performing operation 1 on "zb" generates "zbac".

Return the value of the k-th character in word after performing all the operations. Note that the character 'z' can be changed to 'a' in the second type of operation.

Input & Output

Example 1 — Basic Operations
$ Input: operations = [0,1,1,1], k = 5
Output: b
💡 Note: Start with 'a'. Op[0]: 'a' → 'aa'. Op[1]: 'aa' → 'aabb'. Op[2]: 'aabb' → 'aabbbbcc'. Op[3]: 'aabbbbcc' → 'aabbbbccbbccccdd'. The 5th character is 'b'.
Example 2 — Only Copies
$ Input: operations = [0,0,0], k = 1
Output: a
💡 Note: Start with 'a'. Each operation just copies the string: 'a' → 'aa' → 'aaaa' → 'aaaaaaaa'. The 1st character is always 'a'.
Example 3 — Single Shift
$ Input: operations = [1], k = 2
Output: b
💡 Note: Start with 'a'. Op[1]: shift and append → 'ab'. The 2nd character is 'b'.

Constraints

  • 1 ≤ operations.length ≤ 40
  • operations[i] is either 0 or 1
  • 1 ≤ k ≤ 2operations.length

Visualization

Tap to expand
K-th Character in String Game II INPUT operations[] array: 0 i=0 1 i=1 1 i=2 1 i=3 k = 5 k = 5 Initial word: "a" Operation Types: 0: append copy 1: append next chars ALGORITHM STEPS 1 Work Backwards Start from last op, trace k 2 Track Position Halve length each step 3 Count Increments If k in 2nd half + op=1 4 Calculate Result char = 'a' + count mod 26 Tracing k=5 backwards: i=3: len=16, k=5 in 1st half i=2: len=8, k=5 in 2nd half +1 i=1: len=4, k=1 in 2nd half +1 i=0: len=2, k=1 in 1st half Total increments: 2 'a' + 2 = 'c' FINAL RESULT Final word after all operations: a a b b c c d d 1 2 3 4 5 6 7 8 k=5 Output: 'c' Verification: OK 'a' + 2 increments = 'c' 5th character is 'c' Key Insight: Instead of building the entire string (which doubles each operation), work backwards from position k. Track which half k falls into at each step. If k is in the 2nd half and operation is 1, increment counter. Final answer: 'a' + (total increments mod 26). Time: O(n), Space: O(1) TutorialsPoint - Find the K-th Character in String Game II | Optimized Iterative Approach
Asked in
Google 15 Meta 12 Amazon 8
8.8K Views
Medium Frequency
~25 min Avg. Time
234 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