Sorted Insert Position InterviewBit Solution

Problem: Sorted Insert Position

Problem Description:

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

You may assume no duplicates in the array.

Problem Constraints

1 <= |A| <= 100000
1 <= B <= 109

Input Format

First argument is array A.
Second argument is integer B.

Output Format

Return an integer, the answer to the problem.

Example Input

Input 1:
 A = [1, 3, 5, 6] B = 5 
Input 2:
 A = [1, 3, 5, 6] B = 2 

Example Output:

Output 1:
Output 2:

Example Explanation

Explanation 1:
 5 is found at index 2. 
Explanation 2:
 2 will be inserted at index 1. 


The approach is to find the upper bound of the element. If the element exists then it will return the rightmost position of that element, otherwise, it returns the position of an element just greater than the current element.

Time & Space Complexity

Time Complexity: O(LogN)

- Since we have used a binary search

Space Complexity: O(1)

- Ignoring the given space taken by input array.


Code in C++