Problem Description
Given two positive integers n and k, we build a binary string Sₙ as follows:
- S₁ = "0"
- For i > 1, Sᵢ = Sᵢ₋₁ + "1" + reverse(invert(Sᵢ₋₁)) The problem asks for the kth bit in Sₙ. It is guaranteed that k is valid for the given n.
Key Insights
- The length of Sₙ is 2ⁿ - 1.
- The kth bit's location can be determined by comparing k with the middle position (which is always "1").
- If k is in the left half of Sₙ, it is the same as the kth bit in Sₙ₋₁.
- If k is in the right half, it corresponds to the inverse of a bit in Sₙ₋₁, specifically at position (2ⁿ - k).
Space and Time Complexity
Time Complexity: O(n), where n is the recursion depth. Space Complexity: O(n), due to the recursion stack.
Solution
We solve the problem recursively by leveraging the recursive structure of the binary string.
- Define mid as 2^(n-1), which represents the middle (and always "1") position of Sₙ.
- If k equals mid, return "1".
- If k is less than mid, the kth bit is in the left half; use recursion on Sₙ₋₁.
- If k is greater than mid, find the mirrored index in Sₙ₋₁ using (2ⁿ - k) and invert the result.
- The recursion stops at the base case n = 1, where S₁ is "0".