Binary Search: First Occurrence - aloalgo

Binary Search: First Occurrence

Medium

You are given a sorted array of integers nums that may contain duplicate elements, and a target integer target, your task is to find the index of the first occurrence of the target.

If the target is not found in the array, you should return -1.

You must write an algorithm that is more efficient than a linear search.

Example 1

Inputs
nums = [1, 3, 3, 3, 3, 6, 10, 10, 10, 10]
target = 3
Output
1
Explanation:

The number 3 appears multiple times. The first occurrence is at index 1.

Example 2

Inputs
nums = [2, 4, 10, 10, 10, 18, 20]
target = 10
Output
2
Explanation:

The first occurrence of 10 is at index 2.

Example 3

Inputs
nums = [1, 2, 3, 4, 5]
target = 6
Output
-1
Explanation:

The target 6 is not present in the array.

Loading...
Inputs
nums = [1, 3, 3, 3, 3, 6, 10, 10, 10, 10]
target = 3
Output
1

Hello! I am your ✨ AI assistant. I can provide you hints, explanations, give feedback on your code, and more. Just ask me anything related to the problem you're working on!