DSA interview question
A shipping company prices parcels in fixed weight bands, stored as a sorted array of band limits. For a parcel of weight x, the billing system needs the floor (the largest band limit ≤ x, the band already reached) and the ceil (the smallest band limit ≥ x, the band to charge for). If there is no such value, it reports -1. Both are one binary search each: floor is "last index with value ≤ x" and ceil is the lower bound.
Example: [3, 4, 4, 7, 8, 10], x = 5 → floor 4, ceil 7.
pair<int, int> floorAndCeil(const vector<int>& a, int x); // {floor value, ceil value}; -1 if absent
Input (a, x) | Output | Explanation |
|---|---|---|
([3, 4, 4, 7, 8, 10], 5) | {4, 7} | 5 lies between 4 and 7 |
([3, 4, 4, 7, 8, 10], 8) | {8, 8} | x itself is present |
([3, 4, 4, 7, 8, 10], 2) | {-1, 3} | No value ≤ 2 |
([3, 4, 4, 7, 8, 10], 11) | {10, -1} | No value ≥ 11 |
([5], 5) | {5, 5} |
(Confirm: the array is sorted; values are positive, so -1 unambiguously means "does not exist".)
TreeMap.floorKey / ceilingKey in Java and lower_bound in C++.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