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
Returns (int) 1

Example 2

Input
nums (int[]) = [4,5,6]
size (int) = 3
target (int) = 7
Returns (int) -1

Example 3

Input
nums (int[]) = [9,9,9]
size (int) = 3
target (int) = 9
Returns (int) 0

Use 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

Notifications

Updates are enabled for this browser.

Receive new tutorials, articles and learning resources. You can turn updates off anytime.

Test browser code

Use this code in admin to send a test notification to this browser.