Skip to content

1545. Find Kth Bit in Nth Binary String #723

Answered by kovatz
mah-shamim asked this question in Q&A
Discussion options

You must be logged in to vote

We need to understand the recursive process used to generate each binary string Sn and use this to determine the k-th bit without constructing the entire string.

Approach:

  1. Recursive String Construction:

    • S1 = "0".
    • For i > 1:
      • Si is constructed as:

        Si = Si-1 + "1" + reverse(invert(Si-1))
    • This means Si consists of three parts:
      • Si-1 (the original part)
      • "1" (the middle bit)
      • reverse(invert(Si-1)) (the transformed part)
  2. Key Observations:

    • Si has a length of 2i-1.
    • The middle bit (position 2i-1 of Si is always "1".
    • If k lies in the first half, it falls within Si-1.
    • If k is exactly the middle position, the answer is "1".
    • If k is in the second half, it corresponds to the reverse-inverte…

Replies: 1 comment 2 replies

Comment options

You must be logged in to vote
2 replies
@mah-shamim
Comment options

mah-shamim Oct 19, 2024
Maintainer Author

@kovatz
Comment options

kovatz Oct 19, 2024
Collaborator

Answer selected by mah-shamim
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
question Further information is requested medium Difficulty hacktoberfest hacktoberfest hacktoberfest-accepted hacktoberfest accepted
2 participants