Problem Link - Practice problem - Necklace
Problem Statement:
Your best friend has a necklace with n pearls, each having an integer written on it. She wants to modify the necklace by moving each pearl k spots to the left
. After this modification, you need to print the new order of the pearls on the necklace.
Approach:
The key idea of the code is to use a queue to efficiently simulate the rotation of the pearls. A queue allows us to easily add and remove elements from both ends.
-
We first read the number of test cases and for each test case, the number of pearls (n) and the number of positions (k) to move them.
-
We store all the pearls in a queue. This helps us manage the order of pearls effectively.
-
To rotate the pearls to the left by k positions, we repeatedly remove the front pearl and place it at the back of the queue for k iterations.
-
Finally, we print the pearls in their new order by dequeuing each pearl until the queue is empty.
Time Complexity:
The overall time complexity for each test case is O(n + k), where O(n) accounts for inserting all n pearls into the queue and O(k) for performing k rotations.
Space Complexity:
O(n), as we use a queue to store all n pearls.