Data Structures & AlgorithmsEasyProduct Company SDE · Amazon/Microsoft-style OA

Problem: Return the first index whose value is ≥ x in a sorted array (n if none).

Problem: Return the first index whose value is ≥ x in a sorted array (n if none).
int lowerBound(vector<int>& a, int x) {
    int lo = 0, hi = a.size();
    while (lo < hi) {
        int mid = lo + (hi - lo) / 2;
        if (a[mid] < x) lo = mid + 1;
        else hi = mid;
    }
    return lo;
}
// a = {1, 3, 3, 3, 5, 8}; print lowerBound(a,3), lowerBound(a,4), lowerBound(a,9)
What is printed?
  1. A. 1 4 6
  2. B. 1 3 5
  3. C. 3 4 6
  4. D. 1 4 5

Correct answer: A. 1 4 6

Half-open range [lo, hi): if a[mid] < x the answer is right of mid, otherwise mid itself may be it. First 3 is at index 1; the first value ≥ 4 is 5 at index 4; nothing is ≥ 9 so it returns n = 6. Writing lo + (hi − lo)/2 avoids int overflow of (lo + hi). O(log n).

More Coding Interview Problems questions

Exams that ask this topic