Problem: Sorted Insert Position
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.
1 <= |A| <= 100000 1 <= B <= 109
First argument is array A. Second argument is integer B.
Return an integer, the answer to the problem.
Input 1: A = [1, 3, 5, 6] B = 5
Input 2: A = [1, 3, 5, 6] B = 2
Output 1: 2
Output 2: 1
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++