Given a sorted array of distinct integers and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order.
You must write an algorithm with
Output: 2
Output: 1
Output: 4
Constraints:
1 <= nums.length <= 104 -104 < nums[i], target< 104 nums contains distinct values sorted in ascending order.-104 <= target <= 104
Contents
Solution 1 - Using binary search
In this approach, we will apply
-
If the element at
mid index is the target, then return themid index, since the element is same, it can be inserted at this position. -
If the element at
mid index is greater than target, since the array is sorted in ascending order, this means that the target lies on left half of the array, so we will updateright index tomid-1 . -
If the element at
mid index is less than target, since the array is sorted in ascending order, this means that the target lies on right half of the array, so we will updateleft index tomid+1 .
If that
Complexity Analysis:
Time complexity: Above code runs in O(log n) time where
Space complexity: O(1).
Above implementations source code can be found at