#1545

Find Kth Bit in Nth Binary String

Medium
StringRecursionSimulationRecursionDivide and Conquer
LeetCode ↗

Approaches

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

Intuition

Time O(n)Space O(1)

Instead of constructing the entire string, we can use properties of the binary string's structure to find the k-th bit directly. This reduces the time complexity significantly.

⚙️

Algorithm

4 steps
  1. 1Step 1: Determine the length of S_n, which is 2^n - 1.
  2. 2Step 2: If k is equal to the middle index (2^(n-1)), return '1'.
  3. 3Step 3: If k is less than the middle index, recursively find the k-th bit in S_(n-1).
  4. 4Step 4: If k is greater than the middle index, find the corresponding bit in the inverted part and return its inverted value.
solution.py10 lines
1def findKthBit(n, k):
2    if n == 1:
3        return '0'
4    mid = 2**(n - 1)
5    if k == mid:
6        return '1'
7    elif k < mid:
8        return findKthBit(n - 1, k)
9    else:
10        return '1' if findKthBit(n - 1, 2 * mid - k) == '0' else '0'

Complexity note: The time complexity is O(n) because we only make a constant number of recursive calls proportional to n, without constructing large strings. The space complexity is O(1) since we only use a few variables for calculations.

  • 1The middle bit of S_n is always '1'.
  • 2The structure of S_n allows us to avoid constructing the entire string.

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