DSA interview question
An online store keeps product prices sorted, and its "filter from ₹X upwards" feature needs the first position whose price is at least X; everything from there onward matches the filter. That position is the lower bound of X. It's the most useful variant of binary search, because it answers existence (is a[lb] == x?), insertion position, first occurrence and counting questions. Unlike plain binary search, it always returns a position, which is n if every element is smaller than X.
Example: [3, 5, 8, 15, 19], X = 9 → 3 (the first price ≥ 9 is 15, at index 3).
int lowerBound(const vector<int>& a, int x); // smallest index i with a[i] >= x, or n if none
Input (a, x) | Output | Explanation |
|---|---|---|
([1, 2, 2, 3], 2) | 1 | The first 2 |
([3, 5, 8, 15, 19], 9) | 3 | 15 is the first value ≥ 9 |
([3, 5, 8, 15, 19], 20) | 5 | Every value is smaller: return n |
([3, 5, 8, 15, 19], 1) | 0 | Every value is ≥ 1 |
([1, 2, 2, 3], 3) | 3 | |
([], 4) | 0 | Empty array: n = 0 |
(Confirm: the array is sorted non-decreasingly and may contain duplicates; the result matches std::lower_bound.)
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