#3307
Find the K-th Character in String Game II
HardMathBit ManipulationRecursionRecursionDynamic Programming
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(1) |
💡
Intuition
Time O(n)Space O(1)
Instead of constructing the entire string, we can track the length of the string after each operation. This helps us determine which operation affects the k-th character without building the full string.
⚙️
Algorithm
4 steps- 1Step 1: Initialize the length of the string as 1 (for 'a').
- 2Step 2: Iterate through the operations to calculate the final length of the string after all operations.
- 3Step 3: Determine which operation affects the k-th character by tracing back through the operations.
- 4Step 4: Return the character based on the determined operation.
solution.py20 lines
1def findKthCharacter(k, operations):
2 length = 1
3 for op in operations:
4 if op == 0:
5 length *= 2
6 elif op == 1:
7 length *= 2
8 while length > 1:
9 for op in reversed(operations):
10 if op == 0:
11 if k > length // 2:
12 k -= length // 2
13 length //= 2
14 elif op == 1:
15 if k > length // 2:
16 k -= length // 2
17 else:
18 k = (k - 1) % (length // 2) + 1
19 length //= 2
20 return 'a' if k == 1 else 'b'ℹ
Complexity note: The optimal solution runs in O(n) time because we only iterate through the operations a constant number of times, and we do not build the entire string, just track its length.
- 1Understanding how operations affect string length is crucial.
- 2Simulating operations directly can lead to inefficiencies.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.