420. Find the First Occurrence of Target

EasyBinary SearchArrayBinary Search

Given a sorted array nums (may contain duplicates) and an integer target, return the index of the first (leftmost) occurrence of target. Return -1 if target is not present. Solve in O(log n).

Input: A sorted non-decreasing integer array nums and integer target.

Output: Index of the first occurrence of target, or -1.

Examples

Example 1
Input: [1,2,2,3,3,3,4], 3
Output: 3
Explanation: 3 appears at indices 3,4,5. First occurrence is index 3.
Example 2
Input: [5,5,5,5,5], 5
Output: 0
Explanation: All elements are 5; first occurrence is index 0.
Example 3
Input: [1,2,3,4,5], 9
Output: -1
Explanation: 9 is absent; return -1.

Constraints

Asked by

TCSInfosysWiproCognizantCapgemini
Solve this problem in the editor →