PPractick

DSA interview question

Find How Many Times an Array Has Been Rotated

Easy · Algorithms · Topics: binary search, rotated array

The problem

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).

Function signature

int countRotations(const vector<int>& a);  // distinct values; number of right rotations

Test cases

Input aOutputExplanation
[5, 1, 2, 3, 4]1The minimum is at index 1
[4, 5, 1, 2, 3]2
[1, 2, 3, 4, 5]0Not 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.)

How interviewers phrase it

Clarifying questions to ask

  1. Was it rotated to the right (clockwise) or to the left? (For a left rotation, the answer is (n − index) mod n.)
  2. Are the values distinct?
  3. Is O(log n) required?

Follow-ups to expect

  1. "Why is the rotation count the index of the minimum?"
  2. "How do you find that index?"
  3. "With duplicates?"
  4. "Complexity?"

Practise questions like this with a real engineer

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 interview

Related questions

All 474 dsa interview questions

DSA mock interviews · System design interview questions · Free mock interview practice · Browse interviewers · Sign in