Sort By Kth Bit
You are given an array/list ‘ARR’ of ‘N’ positive integers and an integer ‘K’. Your task is to group all the array elements with ‘K-th’ bit (rightmost bit is ‘1st’ bit) equal to 0 followed by all the elements with ‘K-th’ bit equal to 1.
Note 1: The relative order inside both the groups should remain as it was in the input.
Note 2: You have to return the modified array/list..
For Example :
If ‘ARR’ is {1,2,3,4} and ‘K’ = 1, then after modification, ‘ARR’ should be {2,4,1,3} because ‘K-th’ (‘K’ = 1) of {2,4} is 0 and ‘K-th’ bit of {1,3} is 1.
Input Format :
The first line contains a single integer T representing the number of test cases.
The first line of each test case contains two single space-separated integers ‘N’ and ‘K’ representing size of the input ‘ARR’ and the ‘Kth’ bit as discussed above.
The next line of each test case contains ‘N’ single space-separated integers that represents the elements of the ‘ARR’.
Output Format :
For each test case, return the modified array as discussed above.
Note:
You don’t need to print anything, it has already been taken care of. Just implement the given function.
Follow Up:
Can you do it in linear time?
Constraints:
1 <= T <= 10
1 <= N <= 10^4
1 <= ARR[i] <= 10^9
1 <= K <= 31
Time Limit: 1 sec
CodingNinjas
author
2y
Iteration
The idea is to simply iterate through the ‘ARR’ and check each element whether its ‘K-th’ bit is 0 or 1, and add the element to the respective group.
Here is the algorithm:
- Create an array/li...read more
Help your peers!
Add answer anonymously...
Popular interview questions of Associate Software Engineer
>
NCR Voyix Associate Software Engineer Interview Questions
Stay ahead in your career. Get AmbitionBox app
Helping over 1 Crore job seekers every month in choosing their right fit company
65 L+
Reviews
4 L+
Interviews
4 Cr+
Salaries
1 Cr+
Users/Month
Contribute to help millions
Get AmbitionBox app