#3304

Find the K-th Character in String Game I

Easy
MathBit ManipulationRecursionSimulationExponential GrowthBacktracking
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(log n)
Space
O(1)
O(1)
💡

Intuition

Time O(log n)Space O(1)

Instead of generating the entire string, we can determine the k-th character by understanding the pattern of how characters evolve. Each character's position can be traced back to the original 'a' without constructing the full string.

⚙️

Algorithm

4 steps
  1. 1Step 1: Initialize the current length of the string as 1 (for 'a').
  2. 2Step 2: Calculate the length of the string after each transformation until it exceeds k.
  3. 3Step 3: Determine which segment the k-th character falls into by backtracking through the transformations.
  4. 4Step 4: Calculate the character based on its position in the original string.
solution.py11 lines
1def findKthCharacter(k):
2    length = 1
3    current = 'a'
4    while length < k:
5        length *= 2
6        current = chr(ord(current) + 1)
7    while length > 1:
8        length //= 2
9        if k > length:
10            k -= length
11    return current

Complexity note: The optimal solution runs in O(log n) time because we are effectively halving the length of the string in each iteration, making it very efficient.

  • 1Understanding the exponential growth of the string helps in optimizing the solution.
  • 2Backtracking through the transformations allows us to find the k-th character without full string construction.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.