Problem 373206 · easy · Level 03 Linear Management & Searching

Where the New Book Goes on the Shelf

binary search · arrays

A librarian keeps the catalogue numbers of one shelf in nums, sorted from smallest to largest (the same number can appear more than once). A new book numbered target arrives. Return the index where it must be slotted in so the shelf stays sorted; if books with that number are already there, the new one goes in front of them, so the answer is the index of the first of them.

Examples

Input:  nums = [2, 4, 4, 9, 12], target = 4
Output: 1
Explanation: 4 already occurs; its first occurrence is at index 1.

Input:  nums = [2, 4, 4, 9, 12], target = 5
Output: 3
Explanation: 5 goes between the last 4 and 9.

Input:  nums = [2, 4, 4, 9, 12], target = 13
Output: 5

Constraints

  • 0 <= len(nums) <= 10**6
  • -10**9 <= nums[i], target <= 10**9
  • Aim for O(log n) time with binary search. (A linear scan still passes the tests; the point is to find the position without one.)

Goals

  • Write a leftmost binary search with lo/hi that converge on an index
  • Handle targets smaller or larger than every element
Starting Python…