[Question]: 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 O(log n)
runtime complexity.
Example 1: Input: nums = [1,3,5,6], target = 5 Output: 2 Example 2: Input: nums = [1,3,5,6], target = 2 Output: 1 Example 3: Input: nums = [1,3,5,6], target = 7 Output: 4
// TC: O(log(N))
// SC: O(1)
func findInsertPosition(_ arr: [Int], _ targetElement: Int) -> Int {
let arrayCount = arr.count
var low = 0
var high = arrayCount - 1
var ans = arrayCount// So if element is greater it would be the last
while low <= high {
let mid = (low + high) / 2
// maybe an answer
if arr[mid] >= targetElement {
ans = mid
// look for smaller index on the left
high = mid - 1
} else {
low = mid + 1 // look on the right
}
}
return ans
}
var arrInputInsertPosition = [1,3,5,6]
let elementToInsert = 2
let positionOfLower = findInsertPosition(arrInputInsertPosition, elementToInsert)
print("The positionOfLower index will be ", positionOfLower) // index 1 Because [1,2,3,5,6]