Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Program to find Kth bit in n-th binary string using Python
Suppose we have two positive values n and k. We can construct a binary string S_n using the following rules:
S_1 = "0"
S_i = S_(i-1) concatenate "1" concatenate reverse(invert(S_(i-1))) for i > 1
Here reverse(x) returns the reversed string x, and invert(x) flips all the bits in x (0 becomes 1, 1 becomes 0).
Binary String Generation Pattern
Let's see how these strings are constructed:
S_1 = "0"
S_2 = "011"
S_3 = "0111001"
S_4 = "011100110110001"
Our task is to find the kth bit in S_n. For example, if n = 4 and k = 10, then S_4 = "011100110110001", so the 10th bit is 1 (considering 1-based indexing).
Algorithm Steps
To solve this problem efficiently, we follow these steps:
If k equals 1, return "0" (first bit is always 0)
Otherwise, build the binary strings iteratively until we have enough bits
Use two arrays: one for the current pattern and another for its inverse
Continue building until the string length exceeds k
Example
def solve(n, k):
if k == 1:
return str(0)
else:
arr = [0]
arr2 = [1] # inverse of arr
while k > len(arr):
templast = arr.copy()
temp2last = arr2.copy()
# S_i = S_(i-1) + "1" + reverse(invert(S_(i-1)))
arr = templast + [1] + temp2last
arr2 = templast + [0] + temp2last # inverse pattern
return str(arr[k-1])
# Test the function
n = 4
k = 10
result = solve(n, k)
print(f"The {k}th bit in S_{n} is: {result}")
# Let's also print the complete S_4 string to verify
def build_complete_string(n):
if n == 1:
return "0"
arr = [0]
arr2 = [1]
for i in range(2, n + 1):
templast = arr.copy()
temp2last = arr2.copy()
arr = templast + [1] + temp2last
arr2 = templast + [0] + temp2last
return ''.join(map(str, arr))
s4 = build_complete_string(4)
print(f"S_4 = '{s4}'")
print(f"Position {k}: {s4[k-1]}")
The 10th bit in S_4 is: 1 S_4 = '011100110110001' Position 10: 1
How It Works
The algorithm maintains two arrays:
arr: represents the current binary string S_iarr2: represents the inverted version of S_i
In each iteration, we build the next string by concatenating the previous string, "1", and the reverse of the inverted previous string. This approach avoids actually reversing strings, making it more efficient.
Time and Space Complexity
The time complexity is O(2^n) in the worst case, as the string length grows exponentially. The space complexity is also O(2^n) for storing the binary arrays.
Conclusion
This solution efficiently finds the kth bit in the nth binary string by building the pattern iteratively. The key insight is maintaining both the original and inverted patterns simultaneously to avoid costly string operations.
