Implement binary search for boundary index
Company: Snapchat
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: medium
Interview Round: Onsite
Quick Answer: This question evaluates a candidate's ability to implement binary search for boundary indices, including correct handling of duplicates, providing iterative and recursive variants, and reasoning about time and space complexity.
Constraints
- 0 <= n <= 10^5
- nums is sorted in non-decreasing order
- -10^9 <= nums[i], t <= 10^9
- Return -1 when every element is strictly less than t (including the empty-array case)
Examples
Input: ([1, 3, 5, 7], 4)
Expected Output: 2
Explanation: 5 at index 2 is the first element >= 4.
Input: ([1, 2, 4, 4, 4, 8], 4)
Expected Output: 2
Explanation: Duplicates: the leftmost 4 sits at index 2.
Hints
- Use a half-open search interval [lo, hi) where lo = 0 and hi = n. This lets you cleanly represent the 'insertion point' when no element qualifies.
- On each step, if nums[mid] >= t the answer could be mid or to its left, so move hi = mid; otherwise move lo = mid + 1. Never discard a candidate by setting hi = mid - 1.
- After the loop, lo is the count of elements < t. If lo == n, no element is >= t, so return -1; otherwise lo is the leftmost qualifying index.
- For the follow-up (last element <= t), mirror the logic: find the first index whose value > t, then subtract one (and check it is in bounds).