#3307

Find the K-th Character in String Game II

Hard
MathBit ManipulationRecursionRecursionDynamic Programming
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal 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
  1. 1Step 1: Initialize the length of the string as 1 (for 'a').
  2. 2Step 2: Iterate through the operations to calculate the final length of the string after all operations.
  3. 3Step 3: Determine which operation affects the k-th character by tracing back through the operations.
  4. 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.