Binary Search (and Variants)

Problem

Implement binary search, then extend it to find the first and last occurrence of a target in a sorted array that may contain duplicates.

Input / Output

  • Input: a sorted array nums and a target value.
  • Output: the target's index (plain search), or the first and last indices of the target (variant), or -1 if absent.

Constraints

  • 1 ≤ n ≤ 10^5
  • The array is sorted and may contain duplicates.

Example

[1,2,2,2,3], target=2 -> first=1, last=3
added …
LeaderboardSalaryAccount