PPractick

DSA interview question

Upper Bound

Easy · Algorithms · Topics: binary search, array

The problem

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).

Function signature

int upperBound(const vector<int>& a, int x);  // smallest index i with a[i] > x, or n if none

Test cases

Input (a, x)OutputExplanation
([1, 2, 2, 3], 2)3The first value after the 2s
([3, 5, 8, 9, 15, 19], 9)415 is the first value > 9
([1, 2, 5, 6, 10], 10)5Nothing is greater: return n
([1, 2, 5, 6, 10], 0)0Everything is greater
([2, 2, 2], 2)3
([], 4)0

(Confirm: the array is sorted non-decreasingly; the result matches std::upper_bound.)

How interviewers phrase it

Clarifying questions to ask

  1. Strictly greater than X?
  2. What to return when nothing is greater: n?
  3. Duplicates allowed?

Follow-ups to expect

  1. "What's the one difference from lower bound?"
  2. "How do you find the last occurrence of X?"
  3. "How many elements equal X?"
  4. "How many elements are ≤ X?"
  5. "Complexity?"

Practise questions like this with a real engineer

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 interview

Related questions

All 474 dsa interview questions

DSA mock interviews · System design interview questions · Free mock interview practice · Browse interviewers · Sign in