Problem · Array

First Target Index

Learn this problem
EasyGrammarly logoGrammarlyFULLTIMEPHONE SCREEN

Problem statement

Given a nondecreasing integer array nums and an integer target, return the smallest index i such that nums[i] == target. Return -1 when target does not occur.

Your solution must run in O(log n) time.

Function

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

Examples

Example 1

nums = [1,2,2,2,4]target = 2return = 1

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

Example 2

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

The target does not occur in nums.

Example 3

nums = [7]target = 7return = 0

The only element equals the target.

Constraints

  • 1 <= nums.length <= 100000.
  • -2147483648 <= nums[i], target <= 2147483647.
  • nums is sorted in nondecreasing order.

More Grammarly problems

drafts saved locally
public int firstTargetIndex(int[] nums, int target) {
  // Write your code here.
}
nums[1,2,2,2,4]
target2
expected1
checking account