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
sizeelements. - The array may contain duplicate values.
- Return
-1when the target is missing.
Example 1
Input
nums (int[]) =
[1,2,2,2,3]size (int) =
5target (int) =
2Returns (int)
1Example 2
Input
nums (int[]) =
[4,5,6]size (int) =
3target (int) =
7Returns (int)
-1Example 3
Input
nums (int[]) =
[9,9,9]size (int) =
3target (int) =
9Returns (int)
0Use binary search. When a match is found, store it and keep searching the left half.
Ready to test your solutionRun Code checks your solution against the test cases.Shift + Enter to run