Problem

First and Last Occurrence

Learn this problem
SWSwiggyFULLTIMEONSITE INTERVIEW

Problem statement

You are given a sorted integer array nums and an integer target.

Return an array [first, last], where first is the first index where target appears and last is the last index where target appears.

If target does not appear in nums, return [-1, -1].

Function

findFirstAndLastOccurrence(nums: int[], target: int) → int[]

Examples

Example 1

nums = [5, 7, 7, 8, 8, 10]target = 8return = [3, 4]

The value 8 first appears at index 3 and last appears at index 4.

Example 2

nums = [5, 7, 7, 8, 8, 10]target = 6return = [-1, -1]

The target 6 is not present in the array.

Constraints

  • nums is sorted in non-decreasing order.
drafts saved locally
public int[] findFirstAndLastOccurrence(int[] nums, int target) {
  // write your code here
}
nums[5, 7, 7, 8, 8, 10]
target8
expected[3, 4]
checking account