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?- A. 1 4 6
- B. 1 3 5
- C. 3 4 6
- 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
- Problem: Count how many times a value occurs in a sorted array in O(log n). python from bisect import bisectleft, bisectright a = [2, 4…
- Problem: Search a target in a sorted array of distinct values that has been rotated at an unknown pivot. python def search(a, t): lo, hi =…
- Problem: Find the minimum of a rotated sorted array of distinct values. python def findmin(a): lo, hi = 0, len(a) - 1 while lo < hi: mid =…
- Problem: Packages with weights w (in order) must ship within D days; each day the ship carries a contiguous prefix of the remaining…
- Problem: A courier eats through n ≤ 10⁵ piles of parcels, pile sizes up to 10⁹, at speed k per hour (a pile smaller than k still takes a…
- Problem: Place c routers at given positions on a road so the minimum distance between any two routers is as large as possible. python def…