Last Updated: 30 Oct, 2020

Search Insert Position

Easy
Asked in companies
UberHikeNineleaps Technologies

Problem statement

You are given a sorted array 'arr' of distinct values and a target value 'm'. You need to search for the index of the target value in the array.


Note:
1. If the value is present in the array, return its index.
2. If the value is absent, determine the index where it would be inserted in the array while maintaining the sorted order. 
3. The given array has distinct integers.
4. The given array may be empty.



Example:
Input:  arr = [1, 2, 4, 7],  m = 6 

Output: 3

Explanation: If the given array 'arr' is: [1, 2, 4, 7] and m = 6. We insert m = 6 in the array and get 'arr' as: [1, 2, 4, 6, 7]. The position of 6 is 3 (according to 0-based indexing)


Input Format:
The first line contains two space-separated integers, 'n' and 'm', representing the length of the array and the target integer.

The second line contains 'n' space-separated integers, arr[i] representing the given array.


Output Format:
Print a single line containing a single integer denoting the position of 'm' in the final array on a new line.


Expected Time Complexity:
Try to solve the problem in O(log n).


Constraints:
0 ≤ n ≤ 10 ^ 5
1 ≤ m ≤ 10 ^ 9
1 ≤ arr[i] ≤ 10 ^ 9

Where 'arr[i]' is the array element at index 'i'.

Time Limit: 1 sec.

Approaches

01 Approach

  • Iterate through the given array.
    • If at any position i, we get arr[i] ≥ m, return i.
  • If there is no such position i, return n.

02 Approach

  • Take two pointers L = 0 and R = N - 1 and mid = L + (R - L) / 2, pos = 0.
  • Using binary search, there can be three conditions:
    • arr[mid] == m, return mid.
    • arr[mid] > m, set R = mid - 1. Along with this, set pos = i (since this can be a possible answer)
    • arr[mid] < m, set L = mid + 1.
  • Return the answer which would be pos.