{x}
blog image

Find Kth Bit in Nth Binary String

Given two positive integers n and k, the binary string Sn is formed as follows:

  • S1 = "0"
  • Si = Si - 1 + "1" + reverse(invert(Si - 1)) for i > 1

Where + denotes the concatenation operation, reverse(x) returns the reversed string x, and invert(x) inverts all the bits in x (0 changes to 1 and 1 changes to 0).

For example, the first four strings in the above sequence are:

  • S1 = "0"
  • S2 = "011"
  • S3 = "0111001"
  • S4 = "011100110110001"

Return the kth bit in Sn. It is guaranteed that k is valid for the given n.

 

Example 1:

Input: n = 3, k = 1
Output: "0"
Explanation: S3 is "0111001".
The 1st bit is "0".

Example 2:

Input: n = 4, k = 11
Output: "1"
Explanation: S4 is "011100110110001".
The 11th bit is "1".

 

Constraints:

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

Solution Explanation for Find Kth Bit in Nth Binary String

This problem involves generating a sequence of binary strings and finding a specific bit within a given string in the sequence. Let's break down the solution approaches.

Approach 1: Recursive Approach with Case Analysis

This approach leverages the recursive nature of the string generation. The key observation is that:

  • S<sub>1</sub> = "0"
  • S<sub>i</sub> = S<sub>i-1</sub> + "1" + reverse(invert(S<sub>i-1</sub>))

This means each subsequent string S<sub>i</sub> is built from the previous string S<sub>i-1</sub>. The middle bit is always "1", the first half is S<sub>i-1</sub>, and the second half is the reversed and inverted version of S<sub>i-1</sub>.

The recursive function dfs(n, k) efficiently finds the k-th bit:

  1. Base Cases:

    • If k == 1, the first bit is always "0".
    • If k is a power of 2, the bit is "1" (it's the middle bit added in each step).
  2. Recursive Steps:

    • If k is in the first half of S<sub>n</sub> (k * 2 < 2<sup>n</sup> - 1), recursively search in S<sub>n-1</sub> using dfs(n - 1, k).
    • Otherwise, k is in the second half. We reflect k across the middle (2<sup>n</sup> - k) and invert the result using XOR with 1 (dfs(n - 1, 2<sup>n</sup> - k) ^ 1).

Time Complexity: O(n) - The recursion depth is at most n. Space Complexity: O(n) - Due to the recursive call stack.

Approach 2: Bit Manipulation (Highly Optimized)

This approach uses bit manipulation for a highly efficient solution. The core idea is to directly calculate the bit without explicitly generating the strings. This solution is concise but less intuitive to understand without a deep understanding of bitwise operations. It's highly optimized for speed. The derivation of this formula is complex and would require significant explanation outside the scope of a code explanation. It directly manipulates bits to determine the k-th bit's value.

Time Complexity: O(1) - Constant time. Space Complexity: O(1) - Constant space.

Code Examples (Python, Java, C++, Go, TypeScript)

The code examples below illustrate the recursive approach (Approach 1). Approach 2 (bit manipulation) is provided in TypeScript and JavaScript only due to its conciseness and reliance on bitwise operations which would be less readable in other languages without detailed comments.

Approach 1 (Recursive):

Python:

class Solution:
    def findKthBit(self, n: int, k: int) -> str:
        def dfs(n: int, k: int) -> int:
            if k == 1:
                return 0
            if (k & (k - 1)) == 0: # Check if k is a power of 2
                return 1
            m = 1 << n
            if k * 2 < m - 1:
                return dfs(n - 1, k)
            return dfs(n - 1, m - k) ^ 1
 
        return str(dfs(n, k))

Java:

class Solution {
    public char findKthBit(int n, int k) {
        return (char) ('0' + dfs(n, k));
    }
 
    private int dfs(int n, int k) {
        if (k == 1) return 0;
        if ((k & (k - 1)) == 0) return 1;
        int m = 1 << n;
        if (k * 2 < m - 1) return dfs(n - 1, k);
        return dfs(n - 1, m - k) ^ 1;
    }
}

C++:

class Solution {
public:
    char findKthBit(int n, int k) {
        function<int(int, int)> dfs = [&](int n, int k) {
            if (k == 1) return 0;
            if ((k & (k - 1)) == 0) return 1;
            int m = 1 << n;
            if (k * 2 < m - 1) return dfs(n - 1, k);
            return dfs(n - 1, m - k) ^ 1;
        };
        return '0' + dfs(n, k);
    }
};

Go:

func findKthBit(n int, k int) byte {
	var dfs func(n, k int) int
	dfs = func(n, k int) int {
		if k == 1 {
			return 0
		}
		if k&(k-1) == 0 {
			return 1
		}
		m := 1 << n
		if k*2 < m-1 {
			return dfs(n-1, k)
		}
		return dfs(n-1, m-k)^1
	}
	return byte('0' + dfs(n, k))
}
 

TypeScript:

function findKthBit(n: number, k: number): string {
    const dfs = (n: number, k: number): number => {
        if (k === 1) return 0;
        if ((k & (k - 1)) === 0) return 1;
        const m = 1 << n;
        if (k * 2 < m - 1) return dfs(n - 1, k);
        return dfs(n - 1, m - k) ^ 1;
    };
    return String(dfs(n, k));
}

Approach 2 (Bit Manipulation):

TypeScript:

const findKthBit = (n: number, k: number): string =>
    String((((k / (k & -k)) >> 1) & 1) ^ (k & 1) ^ 1);

JavaScript:

const findKthBit = (n, k) => String((((k / (k & -k)) >> 1) & 1) ^ (k & 1) ^ 1);

Remember to choose the approach that best suits your needs. The recursive approach is more understandable, while the bit manipulation approach offers superior performance for large inputs.