Binary Search

25 min · search()

A sorted list is a quiet superpower: one comparison can rule out half of it.

You're given an integer array nums in strictly increasing order, meaning every value is larger than the one before it, plus an integer target. If target appears, return its zero-based index. If it doesn't, return -1.

A few ground rules:

  • Every value is distinct, so a present target has exactly one index.
  • You should use the sorted order instead of checking every position.
  • The input array stays unchanged.

Constraints

  • 1 <= nums.length <= 100_000
  • -1_000_000_000 <= nums[i], target <= 1_000_000_000
  • nums is strictly increasing.

Hints

Keep a live interval

Track the first and last indices where target could still be. Compare the value halfway between them with target.

Retire half

If the middle value is too small, the middle and everything left of it are too small. If it's too large, the middle and everything right of it are too large.

Know when it's gone

Continue while the interval is valid: left <= right. Once left > right, no candidate remains, so return -1.

Follow-up

How would you change the search to return the index where a missing target should be inserted while keeping the array sorted?

Visible cases

Examples

Example 1

ready
Input
nums = [
  -7,
  -1,
  4,
  9,
  15
]
target = 4
Expected
2
Why
4 sits at zero-based index 2

Example 2

ready
Input
nums = [
  3,
  8,
  12,
  21
]
target = 3
Expected
0
Why
the target can be the first value

Example 3

ready
Input
nums = [
  -5,
  0,
  6,
  14
]
target = 7
Expected
-1
Why
7 falls in a gap and isn't present

Interview signal

Asked at

GoogleAmazonMicrosoft
Loading editor

Console

ready to run

Ready to run.

3 cases are queued.

Run: visible + custom · Submit: full suite