Skip to content
Work Practice Products Coding interviews Machine learning coding Quant developer HFT course Blog Method Why me About Enquire Book a call

Coding · Binary search

Find a value in a sorted array

Easy · Target 10 minutes · Binary search · Type asked atGoogleAmazonBloomberg

Given an array nums of distinct integers sorted in increasing order, and an integer target, return the index of target in nums, or −1 if it is not there. The search must take O(log n) comparisons.

Examples

InputOutputWhy
nums = [-4, 0, 3, 8, 12, 19], target = 83
nums = [-4, 0, 3, 8, 12, 19], target = 5-15 would sit between 3 and 8.
nums = [7], target = 70

Constraints

  • 1 ≤ n ≤ 10⁵
  • −10⁹ ≤ nums[i], target ≤ 10⁹
  • nums is strictly increasing

Hints

Hint 1

Compare target with the middle element. Whichever way the comparison goes, one half of the array cannot contain target.

Hint 2

Keep two indices, lo and hi, with the rule "if target is anywhere, it is in nums[lo..hi]". Every update must keep that rule true.

Hint 3

If nums[mid] < target, then lo = mid + 1; if nums[mid] > target, then hi = mid − 1. Stop when lo > hi: the range is empty.

Where people lose marks

  • Writing while (lo < hi) with hi = mid − 1: the last remaining element is never checked.
  • Setting lo = mid instead of mid + 1: when hi = lo + 1, mid equals lo and the loop never ends.
  • Computing (lo + hi) / 2 in a language with fixed-width integers.
Console⌘/Ctrl + Enter runs

Write a solution and run it against the real test table.


Keep going

Preparing for a real process? Quant interview preparation, or book a free 20-minute call.