255. Search insert position

Given a sorted array of nums consisting 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.

Example 1:

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

Output: 2

Explanation: The target value 5 is found at index 2 in the sorted array. Hence, the function returns 2.

Example 2:

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

Output: 1

Explanation: The target value 2 is not found in the array. However, it should be inserted at index 1 to maintain the sorted order of the array.

Now Your Turn!

Pick the correct output for the given input

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

Still unsure what the problem is asking ?

Let’s go through a few more examples, step by step, to make it clearer.

Constraints:

  •   1 <= nums.length <= 105
  •   -105 <= nums[i] <= 105
  •   nums contains distinct values sorted in ascending order.
  •   -105<= target <= 105

Hints

Frequently Occurring Doubts

Interview Follow-up Questions

0
class Solution {
public:
int searchInsert(vector<int> &nums, int target) {
}
};
Test Case

Input:

Nums
Target