Description:
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.
Solution:
Time Complexity : O(log(n))
Space Complexity: O(1)
// Binary Search
var searchInsert = function(nums, target) {
let left = 0, right = nums.length
while(left < right) {
const mid = left + Math.floor((right - left) / 2)
if(nums[mid]===target) {
return mid
} else if(nums[mid] > target){
right = mid
} else {
left = mid + 1
}
}
return left
};
Top comments (5)
I'm wondering about ' if(nums[mid]===target) { return mid } ' , statement return mid , But while loop won't loops after that In spite of we didn't break while loop ?
nums[mid]===target means that our target number exists in the given array and we only need to return its index. We don't need to do anything else after that.
why return left outside while loop without return left it gives correct answer
On fourth line used const, how it works, cause we can't assign const variable and in this every time loop run const variable value changes.
Since
const midis initialized in the while loop it gets created every time the loop runs a new iteration. Themidvariable is not reassigned, only theleftandrightvariables where reassigned .