DSA interview question
A sorted playlist was shifted to the right K times by a buggy "shuffle" button (each shift moves the last song to the front), and the app wants to know K so it can undo the damage. For an increasing array with distinct values, K is exactly the index of the minimum element: the smallest value started at index 0, and every right rotation moves it one step further. So the problem reduces to finding the minimum of a rotated sorted array, in O(log n).
Example: [4, 5, 1, 2, 3] → 2 (it's [1, 2, 3, 4, 5] rotated right twice).
int countRotations(const vector<int>& a); // distinct values; number of right rotations
Input a | Output | Explanation |
|---|---|---|
[5, 1, 2, 3, 4] | 1 | The minimum is at index 1 |
[4, 5, 1, 2, 3] | 2 | |
[1, 2, 3, 4, 5] | 0 | Not rotated |
[2, 1] | 1 | |
[7] | 0 |
(Confirm: the original array was sorted increasingly with distinct values and rotated to the right K times, with 0 ≤ K < n.)
On Practick another engineer interviews you live for 60 minutes on a question from this bank. They have the full interviewer guide beside the call: the expected answer to every follow-up, hints to give if you stall, and a scoring rubric. You get the model solution once the session settles. It is free: interview someone for an hour and you have earned your own.
Book a free mock interviewAll 474 dsa interview questions
DSA mock interviews · System design interview questions · Free mock interview practice · Browse interviewers · Sign in