Search Insert Position

Easy
Binary Search

Given a sorted array of distinct integers and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order.

You must write an algorithm with O(log n) runtime complexity.

Example 1

Input: nums = [1,3,5,6], target = 5
Output: 2
Explanation: 5 is found at index 2.

Example 2

Input: nums = [1,3,5,6], target = 2
Output: 1
Explanation: 2 would be inserted at index 1.

Example 3

Input: nums = [1,3,5,6], target = 7
Output: 4
Explanation: 7 would be inserted at index 4 (end of array).

Constraints

  • 1 <= nums.length <= 10^4
  • -10^4 <= nums[i] <= 10^4
  • nums contains distinct values sorted in ascending order.
  • -10^4 <= target <= 10^4
Show Hints (3)
Hint 1: This is a variation of binary search where you find the leftmost position where target could be inserted.
Hint 2: When binary search ends without finding the target, the left pointer will be at the correct insertion position.
Hint 3: Think about what happens when target is smaller than all elements, or larger than all elements.
Loading editor...

Test Results

Click "Run" to execute your code against test cases

AI Tutor

Socratic guidance - I'll ask questions, not give answers

AI Tutor
Hello! I'm your AI tutor, here to guide you through this problem using the Socratic method. I won't give you direct answers, but I'll ask questions and provide hints to help you discover the solution yourself. What's your first instinct when you look at this problem? What approach comes to mind?