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 ofwordto itself. - If
operations[i] == 1, generate a new string by changing each character inwordto its next character in the English alphabet, and append it to the originalword.
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:
c
💡 Note:
Start with 'a'. Op[0]: 'a' → 'aa'. Op[1]: 'aa' → 'aabb'. Op[2]: 'aabb' → 'aabbbbcc'. Op[3]: 'aabbbbcc' → 'aabbbbccbbccccdd'. The 5th character is 'c'.
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
Understanding the Visualization
1
Input
operations=[0,1,1,1], k=5
2
String Evolution
String grows: a→aa→aabb→aabbbbcc→aabbbbccbbccccdd
3
Output
5th character is 'c'
Key Takeaway
🎯 Key Insight: Instead of building exponentially large strings, trace backwards from the target position through the operations to determine the final character efficiently.
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code