18 · Binary Search

#35 Search Insert Position

Easysolve on LeetCode ↗

frequently reported atBloombergMicrosoftAmazonGoogle

the problem

In plain words

Given a sorted array of distinct integers and a target, return its index if found; otherwise return the index where it would be inserted to keep the order. Must be O(log n).

in nums = [1,3,5,6], target = 5

out 2

in nums = [1,3,5,6], target = 2

out 1

in nums = [1,3,5,6], target = 7

out 4

Goes after everything — index n.

  • 1 ≤ n ≤ 10⁴
  • -10⁴ ≤ nums[i], target ≤ 10⁴
  • Distinct, sorted ascending

your turn

Try it before you peek

Read the examples, say the brute force out loud, then write code: here or on LeetCode ↗. Stuck for 20 minutes? Open one hint at a time.

Solve it in the browser

LeetCode-style: complete the class. Compiled by the real javac (Java 17) and judged right here — nothing is sent anywhere.

    Solutions are hidden so you can try first. Even 20 minutes of real effort makes the answer stick far better than reading it.

    Marking the problem solved, or opening every hint, also shows it.

    practise next

    Similar problems

    1. #34
    2. #704
      Binary Search
      Easyin Binary Search
    3. #278
      First Bad Version
      Easyin Binary Search