DSA interview question
A log-analysis tool stores event timestamps sorted, and many events can share a timestamp. To show "all events at 10:42:05", it needs the first and last positions of that timestamp in the array, in O(log n), because the logs have hundreds of millions of lines. A single binary search finds an occurrence but not necessarily the first or last. The fix is two boundary searches: one that keeps looking left after a match, and one that keeps looking right.
Example: [5, 7, 7, 8, 8, 10], target 8 → [3, 4].
vector<int> searchRange(const vector<int>& nums, int target); // {first, last}, or {-1, -1}
Input (nums, target) | Output | Explanation |
|---|---|---|
([5, 7, 7, 8, 8, 10], 8) | [3, 4] | |
([5, 7, 7, 8, 8, 10], 6) | [-1, -1] | Not present |
([], 0) | [-1, -1] | |
([2, 2, 2], 2) | [0, 2] | The whole array |
([1, 2, 3], 1) | [0, 0] | A single occurrence |
([1, 2, 3], 3) | [2, 2] | At the end |
(Confirm: the array is sorted non-decreasingly; 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