Search Insert Position

Binary Search, problem 2 of 7

Search Insert Position

Easy

LC #35

binary searchlower bound

Not attempted yet

Given a sorted array nums of distinct integers and a target, return the index of target if it's present. If not, return the index where it would have to be inserted to keep nums sorted.

Aim for O(log n) time.

Example 1

Input: nums = [1,3,5,6], target = 5
Output: 2

Example 2

Input: nums = [1,3,5,6], target = 2
Output: 1

Example 3

Input: nums = [1,3,5,6], target = 7
Output: 4
Explanation: 7 goes after every value.

Constraints

  • 1 <= nums.length <= 10^5
  • -10^9 <= nums[i], target <= 10^9
  • All values are distinct and sorted ascending.

Python

Loading draft…

Test results

8 tests available

No results yet

Run tests your code against the examples; Submit runs the hidden tests too.

3 examples, 5 hidden

Run examples, then submit all tests.