oneby7

Binary Search Lower and upper bounds

227. Search Insert Position

Easy

You are given an array of distinct integers nums, sorted in increasing order, and an integer target. If target is in nums, return its index. If it is not, return the index it would have if it were inserted into nums with the order kept.

Indexes start at 0. You only return the index; nums itself does not change. Aim for a running time of O(log n).

Example 1

Input: nums = [-6, -2, 3, 8, 14, 20], target = 9

Output: 4

Explanation: 9 is not in nums. It belongs after 8 and before 14, so once inserted it would sit at index 4, where 14 is now.

Example 2

Input: nums = [2, 5, 9], target = 40

Output: 3

Explanation: 40 is larger than every element, so it would go after the last one. That is index 3, one past the end of nums.

Example 3

Input: nums = [-1000000000, -50, 0, 50], target = -50

Output: 1

Explanation: −50 is already in nums, at index 1, so the answer is that index.

Check your understanding

Work out the answer for this input before you write any code.

nums = [1, 4, 6, 10], target = 7

Constraints

  • 1 ≤ nums.length ≤ 105
  • -109 ≤ nums[i] ≤ 109
  • nums[i] < nums[i + 1] (strictly increasing, so all values are distinct)
  • -109 ≤ target ≤ 109

Clarifying questions

What you would ask an interviewer before writing any code.

Hints

Interview follow-ups

Runs in your browser
Code
Runs in your browser for now · some things may not work as expectedLn 1, Col 1

Article

Send feedback

Thank you for helping. We read every report and fix what is wrong.

How do you feel about oneby7?

Sign in to oneby7

Keep your progress, your streak and your code, on any device.

New here? This creates your account too.