Update appNew update is available. Click here to update.

Algorithm to find best insert position in sorted array

Last Updated: 30 Oct, 2020
Difficulty: Easy

PROBLEM STATEMENT

Try Problem

You are given a sorted array 'A' of length 'N' with distinct integers and a target integer 'M'. You need to return the position of 'M' if it existed in the array 'A'. If it already exists in 'A', return that position. (0-based indexing)

For example:

If the given array 'A' is: [1, 2, 4, 7] and M = 6. We insert M = 6 in the array and get 'A' as: [1, 2, 4, 6, 7]. The position of 6 is 3 (according to 0-based indexing)
Note:
1) The given array has distinct integers.

2) The given array may be empty.
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, Ai 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.

Note:

You do not need to print anything, it has already been taken care of. Just implement the given function.
Constraints:
0 ≤ N ≤ 10 ^ 5
1 ≤ M ≤ 10 ^ 9
1 ≤ Ai ≤ 10 ^ 9

Where 'Ai' is the array element at index 'i'.

Time Limit: 1 sec.
Follow up:
Try to solve the problem in O(log N).

Approach 1

  • Iterate through the given array.
    • If at any position i, we get A[i] ≥ M, return i.
  • If there is no such position i, return N.
Try Problem