Find in a Sorted List

EasyBinary Search≈ 15 min

You are given a list of distinct integers nums, sorted from smallest to largest, and a number target. Return the index of target in the list, or -1 if it is not there.

Examples

text
nums = [1, 3, 5, 7, 9], target = 7   →  3
nums = [1, 3, 5, 7, 9], target = 4   →  -1
nums = [2], target = 2               →  0

Constraints

  • Between 0 and 100,000 numbers, sorted and distinct.
  • Aim for O(log n): a list four times longer should take only a couple of steps more, not four times as long. Python's list.index and in, and TypeScript's indexOf, read the list from the start.
Sound off. Turn on for key clicks and a chime when the tests pass.Inline suggestions off. Recommended while you are learning. Turn on to complete words as you type.
Console
›Run to see what your code prints

Run checks the 3 visible cases here, in your browser. Submit runs all 7 on the judge, 4 of them hidden, and measures how your solution scales.