Binary Search Variants - Problem
Given a sorted array of integers nums and a target value, implement three binary search variants:
1. Find First Occurrence: Return the index of the first occurrence of target, or -1 if not found
2. Find Last Occurrence: Return the index of the last occurrence of target, or -1 if not found
3. Count Occurrences: Return the total count of target in the array
Your solution should return an array [first, last, count] where:
firstis the index of first occurrencelastis the index of last occurrencecountis the total number of occurrences
All three values should be -1, -1, 0 respectively if target is not found.
Input & Output
Example 1 — Multiple Occurrences
$
Input:
nums = [5,7,8,8,8,8,9], target = 8
›
Output:
[2,5,4]
💡 Note:
Target 8 first appears at index 2, last appears at index 5, total count is 4 occurrences
Example 2 — Single Occurrence
$
Input:
nums = [1,2,3,4,5], target = 3
›
Output:
[2,2,1]
💡 Note:
Target 3 appears only once at index 2, so first=last=2, count=1
Example 3 — Not Found
$
Input:
nums = [1,2,3,4,5], target = 6
›
Output:
[-1,-1,0]
💡 Note:
Target 6 is not in the array, so return [-1,-1,0]
Constraints
- 1 ≤ nums.length ≤ 105
- -109 ≤ nums[i] ≤ 109
- nums is sorted in non-decreasing order
- -109 ≤ target ≤ 109
Visualization
Tap to expand
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code