Insert Position

Let's solve one basic problem and test our approach. Difficulty Level: Easy

Problem statement

We are given a sorted array of distinct integers and a target value. We will return the index if the target is found. Otherwise, we will return the index to where it would be if it were inserted in order.

Constraints:

  • 1nums.length1031 \leq nums.length \leq 10^3
  • 103nums[i]103-10^3 \leq nums[i] \leq 10^3
  • numsnums contains distinct values, sorted in ascending order.
  • 103target103-10^3 \leq target \leq 10^3

Example 1: General case

Input: [2,4,5,9,11], 5    
Output: 2

Example 2: Missing element case

Input: [2,4,5,9,11], 3    
Output: 1

Example 3: Insert to the end of the array

Input: [2,4,5,9,11], 15    
Output: 5

Example 4: Insert to the beginning of the array

Input: [2,4,5,9,11], -1    
Output: 0

Level up your interview prep. Join Educative to access 70+ hands-on prep courses.