DSA interview question
A circular log buffer stores message IDs in increasing order, but because it wraps around, the array in memory looks like [4, 5, 6, 7, 0, 1, 2]: sorted, then rotated at an unknown point. Given an ID, the system must find its index in O(log n). Plain binary search fails because the array isn't sorted as a whole, but at every midpoint at least one half is sorted. Check whether the target lies inside that sorted half's range, and you know which half to discard.
Example: [4, 5, 6, 7, 0, 1, 2], target 0 → 4.
int searchRotated(const vector<int>& nums, int target); // distinct values; index or -1
Input (nums, target) | Output | Explanation |
|---|---|---|
([4, 5, 6, 7, 0, 1, 2], 0) | 4 | |
([4, 5, 6, 7, 0, 1, 2], 3) | -1 | Not present |
([1], 0) | -1 | |
([1], 1) | 0 | |
([3, 1], 1) | 1 | Two elements, rotated |
([5, 1, 3], 5) | 0 | |
([4, 5, 6, 7, 8, 1, 2, 3], 8) | 4 | Just before the rotation point |
(Confirm: the values are distinct and the array is a rotation of an increasing array; O(log n) is required.)
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