DSA interview question
A dictionary app stores a million words in sorted order and needs to check whether a typed word exists, instantly, on every keystroke. Scanning the list is O(n); binary search looks at the middle element, discards the half that can't contain the target, and repeats, so it needs about 20 comparisons for a million entries. It's simple to describe but famously easy to get wrong (Jon Bentley found most professional programmers' versions had bugs), usually through off-by-one boundaries or an overflowing midpoint.
Example: [-1, 0, 3, 5, 9, 12], target 9 → index 4.
int binarySearch(const vector<int>& a, int target); // index of target in sorted, distinct a, or -1
Input (a, target) | Output | Explanation |
|---|---|---|
([-1, 0, 3, 5, 9, 12], 9) | 4 | |
([-1, 0, 3, 5, 9, 12], 2) | -1 | Not present |
([5], 5) | 0 | |
([5], -5) | -1 | |
([1, 2, 3, 4, 5, 6, 7, 8], 1) | 0 | First element |
([1, 2, 3, 4, 5, 6, 7, 8], 8) | 7 | Last element |
([], 1) | -1 | Empty array |
(Confirm: the array is sorted in increasing order with distinct values.)
lo + (hi − lo) / 2 instead of (lo + hi) / 2?"lo <= hi and not lo < hi?"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