Skip to main content
Back to problems
Leetcode
Medium
Strings
Recursion
Bit Manipulation
Google
Find Kth Bit In Nth Binary String

Find the kk-th bit in a recursively defined binary string of length 2n12^n-1.

Acceptance 0%
Also Available On
Other platform versions and source mappings for the same problem.

Find K-th Bit in N-th Binary String

gfg
Problem Statement

Problem

You are given two integers nn and kk.

Define a binary string SnS_n recursively as follows:

  • S1="0"S_1 = "0"
  • For n>1n > 1, construct SnS_n by taking Sn1S_{n-1}, appending a 0, then appending the reverse of Sn1S_{n-1} with every bit flipped (0 becomes 1, and 1 becomes 0).

Your task is to return the kk-th character of SnS_n using 1-based indexing.

This problem is designed to test your ability to reason about recursive structure without explicitly building the full string.

Input Format

  • Two integers nn and kk.
  • nn is the recursion level.
  • kk is the 1-based position to query in SnS_n.

Output Format

  • Return the character at position kk in SnS_n.
  • The answer is either 0 or 1.

Constraints

  • 1n1 \le n
  • 1k2n11 \le k \le 2^n - 1
  • The intended solution should avoid constructing the full string for large nn.
Examples
Sample cases returned by the problem API.

Example 1

Input

n = 3, k = 1

Output

0

Explanation

S3=0111001S_3 = 0111001, so the first bit is 0.

Example 2

Input

n = 3, k = 5

Output

0

Explanation

S3=0111001S_3 = 0111001, and the 5th bit is the middle bit 0.

Show 1 more example

Example 3

Input

n = 4, k = 11

Output

1

Explanation

The recursive string S4S_4 has length $15$. Tracing the position through mirrored halves gives bit 1 at index 11.

Premium problem context

Unlock deeper context for this problem

Premium adds guided hints, editorial links, similar variants, discussion resources, and concept maps so you can understand why a problem matters, not just solve it once.

Guided hints
Editorial and discussion links
Concept map and variants
Sign in to unlock
Track your progress
Sign in to bookmark this problem, save notes, and manage its revision plan.