First occurrence or floor index in a sorted array

0
Sign in

You are given an array nums of integers sorted in non-decreasing order. It may contain repeated values. You are also given an integer target.

Implement search_first_or_floor(nums, target) -> int:

  • If target appears in nums, return the index of its first occurrence.
  • Otherwise, return the index of the closest element that is less than or equal to target (its floor). If that value repeats, return the copy nearest to where target would be inserted, which is its last copy.
  • If every element is greater than target (or nums is empty), return -1.

Your solution should run in O(log n) time.

Constraints

  • 0 <= len(nums) <= 10^5
  • -10^9 <= nums[i], target <= 10^9
  • nums is sorted in non-decreasing order.

Example 1

nums = [4, 6, 6, 6, 11], target = 6
Output: 1

6 appears at indices 1, 2 and 3, so the first occurrence is index 1.

Example 2

nums = [4, 6, 6, 6, 11], target = 9
Output: 3

9 is absent. The largest value not above it is 6, and its copy nearest the insertion point is at index 3. For target = 2 the answer would be -1.

Reconstructed from the reported question; details may differ from what interviewers ask.

MicrosoftCodingMedium

Sign in to see the worked answer

The full answer, chapter by chapter, with what interviewers expect at each level. Free with an account: one full answer per company.