Given a pack of 2^N cards (0 … 2^N – 1), shuffle it in N steps. At step k (0 < k < N) we divide the deck into 2k equal-sized decks. Each one of those decks is reordered by having all the cards that lie on even positions first, followed by all cards that lie on odd positions (the order is preserved in each one of the two subsequences). Now, we are given a key (index). We have to answer the card on that position (0-based indexing). Examples:
Input : N = 3 (Size = 2^N), Key = 3 Output : 6 Explanation : Pack : 0 1 2 3 4 5 6 7 Shuffle 1 : 0 2 4 6|1 3 5 7 Shuffle 2 : 0 4|2 6|1 5|3 7 Card at index 3 : 6
Method 1 : We can simply simulate the whole process and find the exact order of the cards after all the N shuffles are done.
Time Complexity : O(N * 2^N)
Method 2 :
Let us try to find the binary representation of Key and the final answer and try to spot some observations based on it.
Let N = 3
Below is the table :
It is clearly visible that the answer is the reverse of binary representation of Key.
This article is contributed by Rohit. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Don’t stop now and take your learning to the next level. Learn all the important concepts of Data Structures and Algorithms with the help of the most trusted course: DSA Self Paced. Become industry ready at a student-friendly price.
- Best way to answer If an Interviewer asks about Salary Expectation to you as a Fresher
- Range query for count of set bits
- Query to count odd and even parity elements in subarray after XOR with K
- Queries for count of array elements with values in given range with updates
- Sum of first N natural numbers with all powers of 2 added twice
- Types of Antialiasing Techniques
- Sum of Hamming difference of consecutive numbers from 0 to N | Set 2
- First number to leave an odd remainder after repetitive division by 2
- Advantages and Disadvantages of Auto-CAD
- Construct the smallest possible Array with given Sum and XOR
- XOR of a subarray (range of elements) | Set 2
- Maximum bitwise OR value of subsequence of length K
- Largest number M less than N such that XOR of M and N is even
- Count of 0s to be flipped to make any two adjacent 1s at least K 0s apart