← Home

1545. Find Kth Bit in Nth Binary String

LeetCode article · C++ solution
Website made by wuisabel-gif · Original C++ code by keineahnung2345
two pointersC++Markdown
154

This is one of those problems where the clean idea matters more than the amount of code. For 1545. Find Kth Bit in Nth Binary String, the solution in this repository is mainly a two pointers solution.

Guide

What?

The first job is to translate the English prompt into state, transition, and stopping conditions. Instead of trying to be clever immediately, read the code as a sequence of questions:

  • What state are we keeping?
  • How do we move from one state to the next?
  • When do we know the answer is already determined?

For this file, the main tools are: two pointers, sliding window, bit manipulation.

Guide

When?

This pattern shows up when the brute force version has too many repeated checks, too many possible branches, or too much bookkeeping to do by hand. The accepted code reduces that pressure by storing exactly the information that remains useful later.

The important function names to track are reverse, invert, becomes.

Guide

Why?

The point of the implementation is not to make the code longer. It is to avoid doing the same thinking twice.

  • The final return is not magic; it is the invariant after the loops or recursion have finished doing their accounting.

Guide

How?

Walk through the solution in this order:

  1. Start from the smallest reliable state.
  2. Expand one legal move at a time.
  3. Cache, count, or merge information as soon as it becomes settled.
  4. Let the final stored value answer the original question.

The most important competitive-programming habit here is to trust the invariant. Once the invariant is right, the loops become much less scary.

Guide

Complexity

  • Time: O(n) to O(n log n), depending on the dominant loop or data structure operation
  • Space: O(n) in the usual case for auxiliary containers or recursion

Guide

C++ Solution

Your submission

The accepted solution

solution.cpp
01//Runtime: 244 ms, faster than 16.67% of C++ online submissions for Find Kth Bit in Nth Binary String.
02//Memory Usage: 58.1 MB, less than 66.67% of C++ online submissions for Find Kth Bit in Nth Binary String.
03class Solution {
04public:
05    string reverse(string s){
06        return string(s.rbegin(), s.rend());
07    }
08    
09    string invert(string& s){
10        string ret;
11        ret.resize(s.size());
12        transform(s.begin(), s.end(), ret.begin(), 
13            [](char c){return (c == '1') ? '0' : '1';});
14        return ret;
15    }
16    
17    char findKthBit(int n, int k) {
18        string s = "0";
19        
20        for(int i = 2; i <= n && s.size() < k; ++i){
21            s = s + "1" + reverse(invert(s));
22            // cout << s << endl;
23        }
24        
25        // cout << s << endl;
26        
27        return s[k-1];
28    }
29};
30
31//Recursion
32//https://leetcode.com/problems/find-kth-bit-in-nth-binary-string/discuss/780984/Java-Recursive-Solution
33//Runtime: 0 ms, faster than 100.00% of C++ online submissions for Find Kth Bit in Nth Binary String.
34//Memory Usage: 6.2 MB, less than 66.67% of C++ online submissions for Find Kth Bit in Nth Binary String.
35class Solution {
36public:
37    char findKthBit(int n, int k) {
38        if(n == 1){
39            //stop condition
40            return '0';
41        }
42        /*
43        n = 1, len = 1
44        n = 2, len = 1*2+1 = 3
45        n = 3, len = 3*2+1 = 7
46        n = 4, len = 7*2+1 = 15
47        */
48        int len = (1<<n) - 1;
49        
50        //note that k is 1-based!
51        if(k == (len>>1)+1){
52            return '1';
53        }else if(k < (len>>1)+1){
54            //left part
55            return findKthBit(n-1, k);
56        }else{
57            //right part
58            /*
59            kth bit in the original string
60            becomes (l-k+1)th bit in the reverted string
61            */
62            //and we also need to invert it
63            return findKthBit(n-1, len-k+1) == '0' ? '1' : '0';
64        }
65    }
66};
67
68//Iterative
69//https://leetcode.com/problems/find-kth-bit-in-nth-binary-string/discuss/781181/JavaC%2B%2BPython-Iterative-Solutions
70//Runtime: 0 ms, faster than 100.00% of C++ online submissions for Find Kth Bit in Nth Binary String.
71//Memory Usage: 6.1 MB, less than 66.67% of C++ online submissions for Find Kth Bit in Nth Binary String.
72class Solution {
73public:
74    char findKthBit(int n, int k) {
75        int flipped = 0, len = (1<<n)-1;
76        
77        while(k > 1){
78            // cout << k << endl;
79            if(k == (len>>1)+1){
80                return (!flipped) ? '1' : '0';
81            }
82            
83            //prepare for next iteration
84            
85            if(k > (len>>1)+1){
86                //in the right part of current string
87                k = len-k+1;
88                flipped ^= 1;
89            }
90            
91            len >>= 1;
92        }
93        
94        //now k is equal to 1, meaning the first bit of the string
95        
96        /*
97        1st bit(1-based) is always '0', 
98        and we have flipped many times
99        */
100        return '0' + flipped;
101    }
102};

Cost

Complexity

Time
O(n) to O(n log n), depending on the dominant loop or data structure operation
Dominated by the main traversal, recursion, or data-structure operations in the code.
Space
O(n) in the usual case for auxiliary containers or recursion
Auxiliary state plus the answer structure where the problem requires one.