LeetCode 1545: Find Kth Bit in Nth Binary String Solution
Master LeetCode problem 1545 (Find Kth Bit in Nth Binary String), a medium challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.
1545. Find Kth Bit in Nth Binary String
Problem Explanation
Explanation:
To solve this problem, we can observe that the binary strings follow a recursive pattern based on the previous string. We can simulate the generation of each string up to the nth string and then find the kth bit in the final string.
- Start with the base case: S1 = "0".
- For i > 1, generate Si based on Si-1 using the given formula.
- Repeat this process for n iterations to generate Sn.
- Finally, return the kth bit in Sn.
Time complexity: O(2^n)
Space complexity: O(2^n)
:
Solution Code
class Solution {
public char findKthBit(int n, int k) {
return generateString(n).charAt(k - 1);
}
private String generateString(int n) {
if (n == 1) {
return "0";
}
String prev = generateString(n - 1);
return prev + "1" + invertAndReverse(prev);
}
private String invertAndReverse(String s) {
StringBuilder sb = new StringBuilder();
for (char c : s.toCharArray()) {
sb.append(c == '0' ? '1' : '0');
}
return sb.reverse().toString();
}
}Try It Yourself
Loading code editor...
Related LeetCode Problems
Frequently Asked Questions
How to solve LeetCode 1545 (Find Kth Bit in Nth Binary String)?
This page provides optimized solutions for LeetCode problem 1545 (Find Kth Bit in Nth Binary String) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.
What is the time complexity of LeetCode 1545 (Find Kth Bit in Nth Binary String)?
The time complexity for LeetCode 1545 (Find Kth Bit in Nth Binary String) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 1545 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 1545 in Java, C++, or Python.