Skip to content
Decoder

Search Insert Position

Easy

Problem

You are given a list nums of distinct integers sorted in increasing order and a value target. If target is in nums, return its index. If not, return the index where it would be inserted to keep the list sorted. Your solution should run in O(log n) time.

Example 1

Input
nums = [2, 4, 7, 9], target = 7
Output
2

Example 2

Input
nums = [2, 4, 7, 9], target = 5
Output
2
Why
between 4 and 7

Example 3

Input
nums = [2, 4, 7, 9], target = 10
Output
4
Why
after the end

Constraints

  • 1 <= nums.length <= 10^4
  • -10^4 <= nums[i], target <= 10^4
  • nums is sorted in increasing order with no repeats.

Read it once before you touch anything

Want some pressure? Start the timer. In an interview you get about two minutes to understand the problem.

  1. 1Read the goalWhat goes in, what comes out
  2. 2Scan the examplesCheck one by hand
  3. 3Note the constraintsThey set your Big O
Say what it asks in one sentence
Say it out loud first, then compare with ours.