Problem · Array

Find the First Target Index

Learn this problem
EasySuperhuman logoSuperhumanFULLTIMEPHONE SCREEN

Problem statement

Given a nondecreasing array of integers nums and an integer target, return the smallest index i such that nums[i] == target.

If target does not appear in nums, return -1.

Function

firstIndex(nums: int[], target: int) → int

Examples

Example 1

nums = [1,2,2,2,5,8]target = 2return = 1

The target appears at indices 1, 2, and 3, so the first index is 1.

Example 2

nums = [-5,-1,0,4,4,9]target = 4return = 3

The first value equal to 4 is at index 3.

Example 3

nums = [1,3,5,7]target = 4return = -1

No array value equals 4, so the result is -1.

Constraints

  • 0 <= nums.length <= 10^5.
  • -2^31 <= nums[i], target <= 2^31 - 1.
  • nums is sorted in nondecreasing order.
  • Your algorithm should run in O(log n) time.

More Superhuman problems

drafts saved locally
public int firstIndex(int[] nums, int target) {
  // write your code here
}
nums[1,2,2,2,5,8]
target2
expected1
checking account