Practice · Binary search · 1 of 5

Find a Number in a Sorted List

You are given a list nums of different integers, sorted from smallest to largest, and an integer target. Return the index of target in nums (counting from 0), or -1 if it isn't there.

Your solution should take O(log n) time.

Example 1

Input
nums = [-4, 0, 3, 8, 12, 20], target = 8
Output
3

Example 2

Input
nums = [-4, 0, 3, 8, 12, 20], target = 5
Output
-1
5 would sit between 3 and 8, but it isn't there.

Constraints

  • nums holds 1 to 10⁴ numbers, all different, in increasing order.
  • Every number, and target, is between −10⁴ and 10⁴.