DSA interview question
The same store's "filter up to ₹X" feature needs the first position whose price is strictly greater than X; everything before it is affordable. That position is the upper bound of X. Together with the lower bound, it answers many range questions at once, for example: how many items cost exactly X? That's upperBound − lowerBound. The only difference from lower bound is a single comparison, > instead of >=, which is precisely why the two are easy to mix up.
Example: [3, 5, 8, 9, 15, 19], X = 9 → 4 (the first price above 9 is 15, at index 4).
int upperBound(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) | 3 | The first value after the 2s |
([3, 5, 8, 9, 15, 19], 9) | 4 | 15 is the first value > 9 |
([1, 2, 5, 6, 10], 10) | 5 | Nothing is greater: return n |
([1, 2, 5, 6, 10], 0) | 0 | Everything is greater |
([2, 2, 2], 2) | 3 | |
([], 4) | 0 |
(Confirm: the array is sorted non-decreasingly; the result matches std::upper_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