Find Kth Bit in Nth Binary String

MediumMathmath

Solve this the way you would in the interview: out loud, on a timer, with an AI interviewer asking follow-ups while you code. You get a scored report at the end.

Practice this as a mock interviewFree to start, no account needed

Problem

Binary strings S1, S2, ... are built as follows: S1 = "0", and for i > 1, Si = S(i-1) + "1" + reverse(invert(S(i-1))). Here invert flips every bit and reverse reverses the string. For example S2 = "011", S3 = "0111001", and S4 = "011100110110001". Sn has length 2^n - 1. Given n and a 1-indexed position k with 1 <= k <= 2^n - 1, return the k-th character of Sn as a single character, '0' or '1'. Try to answer without building the whole string, in O(n) time.

Examples

Input: n = 3, k = 1
Output: "0"
S3 is 0111001, whose first character is 0.
Input: n = 4, k = 11
Output: "1"
S4 is 011100110110001, whose 11th character is 1.
Input: n = 2, k = 2
Output: "1"
S2 is 011; the middle character is 1.

Constraints

  • 1 <= n <= 20
  • 1 <= k <= 2^n - 1

What the interviewer grades

A correct solution is one of five scores. The report also grades problem understanding (did you clarify inputs and edge cases before coding), problem solving, communication while you work, code quality, and testing. See a sample report, or read up on the pattern in the lessons.

More math problems