Learner Level

Implement the method firstOccurrence that returns the first index of a target value in a sorted array.

Given a sorted integer array, return the first zero-based index where target appears.

The task is designed to test careful handling of edge cases, not only the most common input.

  • Use only the first size elements.
  • The array may contain duplicate values.
  • Return -1 when the target is missing.
Example 1
Input:
nums (int[]) = [1,2,2,2,3]
size (int) = 5
target (int) = 2
Return:
(int) 1
Example 2
Input:
nums (int[]) = [4,5,6]
size (int) = 3
target (int) = 7
Return:
(int) -1
Example 3
Input:
nums (int[]) = [9,9,9]
size (int) = 3
target (int) = 9
Return:
(int) 0

Use binary search. When a match is found, store it and keep searching the left half.

Run your code to see the result.