What will be the ‘k-th’ bit?

Posted: 12 Mar, 2021
Difficulty: Moderate


Try Problem

You are given two integers, ‘N’ and ‘K’. Your task is to return the ‘K-th’ bit in row ‘N’ of the given sequence.

Sequence: The first row contains a single bit ‘1’. In each subsequent row, we look at the previous row and replace each ‘1’ with ‘10’ and each ‘0’ with ‘01’.

N = 4, K = 5

Given sequence:
The previous row’s ‘1’ becomes ‘10’, and ‘0’ becomes ‘01’ for each subsequent row. The contents of each row are:
Row 1: 1
As, ‘1’ => ‘10’, So ‘1’ (row 1) => ‘10’ (row 2)

Row 2: 10
As ‘1’ => ‘10’& ‘0’ => ‘01’,So ‘10’ (row 2) => ‘1001’ (row 3)

Row 3: 1001
As ‘10’ => ‘1001’ & ‘01’ => ‘0110’, So ‘1001’ (row 3) => ‘10010110’ (row 4)

Row 4: 10010110
The ‘5-th’ bit in row ‘4’ is ‘0’. Return ‘0’ as the answer.
Both ‘K’ and ‘N’ have 1-based indexing.
Input format:
The first line of input contains an integer ‘T’ which denotes the number of test cases. Then, the ‘T’ test cases follow.

The first and only line of each test case contains two space-separated integers, ‘N’ and ‘K’, denoting the row number and index of the bit you need to return.
Output format:
For every test case, print a single line containing a single integer (0 or 1) representing the ‘K-th’ bit in the row ‘N’.


You do not need to input or print anything, as it has already been taken care of. Just implement the given function.
1 <= T <= 10 ^ 4
1 <= N <= 30
1 <= K <= 2 ^ (N - 1)

Where ‘T’ is the number of test cases, ‘N’ is the row number, and ‘K’ is the bit index.

Time limit: 1 second.
Approach 1

We can view the given sequence as a binary tree with the root node as ‘1’. When a node is ‘1’, it has two children nodes as ‘1’ and ‘0’, and when it is ‘0’, the two children nodes are ‘0’ and ‘1’. If ‘k’ is odd, then the current node is the first child, else it’s the second child. The first child node has the same value as the parent node, and the second child node has the opposite value. The current node’s value depends on the parent node, so we need a recursive function that keeps going to the parent node until we reach the root node/ first row (whose node value is ‘1’). Another observation, the first row is always a single ‘1’, so the first bit of each row subsequent rows will also be ‘1’. Hence, we don’t always need to go to the first row. Instead, we check if the parent node stores the first bit in that row (the first bit is ‘1’). We call the given ‘kthValue’ function recursively to get the value stored at ‘k-th’ bit.


  • If ‘k’ is equal to ‘1’, return ‘1’.
  • If ‘k’ is odd, then:
    • ‘parent = kthValue(n - 1, (k+1)/2)’.
  • If ‘k’ is even, then:
    • ‘parent = kthValue(n - 1, k/2)’.
    • ‘parent = parent XOR 1’. As ‘k’ is even the current node stores the opposite value as ‘parent’/the previous row. Here, ‘XOR’ means bitwise xor.
  • Return ‘parent’ as the answer.
Try Problem