Find Kth Bit in Nth Binary String

medium string recursion divide and conquer

Problem

Build a sequence of binary strings where S1 = "0" and, for i > 1, Si = Si-1 + "1" + reverse(invert(Si-1)). Here invert flips every bit (0↔1) and reverse reverses the string. Given n and a 1-based index k, return the kth character of Sn as "0" or "1", without materializing the whole string.

Inputn = 4, k = 11
Output"1"
S₄ = "0111001101 1 0001"; the 11th character is "1".
Inputn = 3, k = 1
Output"0"
S₃ = " 0 111001"; the 1st character is "0".

def find_kth_bit(n, k):
    length = (1 << n) - 1   # length of S_n
    invert = 0
    while length > 1:
        mid = (length + 1) // 2
        if k == mid:
            return "0" if invert else "1"   # middle bit is "1"
        if k > mid:
            k = length - k + 1   # mirror into left half
            invert ^= 1          # right half is reverse(invert(left))
        length = (length - 1) // 2   # shrink to S_(i-1)
    return "1" if invert else "0"    # base bit S_1 is "0"
function findKthBit(n, k) {
  let length = (1 << n) - 1;   // length of S_n
  let invert = 0;
  while (length > 1) {
    const mid = (length + 1) / 2;
    if (k === mid) {
      return invert ? "0" : "1";   // middle bit is "1"
    }
    if (k > mid) {
      k = length - k + 1;   // mirror into left half
      invert ^= 1;          // right half is reverse(invert(left))
    }
    length = (length - 1) / 2;   // shrink to S_(i-1)
  }
  return invert ? "1" : "0";   // base bit S_1 is "0"
}
char findKthBit(int n, int k) {
    int length = (1 << n) - 1;   // length of S_n
    int invert = 0;
    while (length > 1) {
        int mid = (length + 1) / 2;
        if (k == mid) {
            return invert == 1 ? '0' : '1';   // middle bit is '1'
        }
        if (k > mid) {
            k = length - k + 1;   // mirror into left half
            invert ^= 1;          // right half is reverse(invert(left))
        }
        length = (length - 1) / 2;   // shrink to S_(i-1)
    }
    return invert == 1 ? '1' : '0';   // base bit S_1 is '0'
}
char findKthBit(int n, int k) {
    int length = (1 << n) - 1;   // length of S_n
    int invert = 0;
    while (length > 1) {
        int mid = (length + 1) / 2;
        if (k == mid) {
            return invert ? '0' : '1';   // middle bit is '1'
        }
        if (k > mid) {
            k = length - k + 1;   // mirror into left half
            invert ^= 1;          // right half is reverse(invert(left))
        }
        length = (length - 1) / 2;   // shrink to S_(i-1)
    }
    return invert ? '1' : '0';   // base bit S_1 is '0'
}
Time: O(n) Space: O(1)