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:

  • first is the index of first occurrence
  • last is the index of last occurrence
  • count is 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
Binary Search Variants - Find First, Last, and CountINPUTSorted Array & Target5788901234Target: 8Need to find:• First occurrence index• Last occurrence index• Total count of targetALGORITHMTwo Binary Searches1Binary Search for FirstWhen target found, search left2Binary Search for LastWhen target found, search right3Calculate Countcount = last - first + 14Return Results[first, last, count]Time: O(log n)Two binary searchesRESULTFirst, Last, Count[2, 3, 2]First: 2Last: 3Count: 2Target 8 appears:• First at index 2• Last at index 3• Total 2 occurrences✓ Efficient O(log n)vs O(n) linear scanKey Insight:Two specialized binary searches (find-first pushing left, find-last pushing right) solve all threerequirements in O(log n) time, much faster than O(n) linear scanning.TutorialsPoint - Binary Search Variants | Two Specialized Binary Searches
Asked in
Amazon 85 Google 72 Microsoft 68 Facebook 45
89.5K Views
High Frequency
~25 min Avg. Time
2.8K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen