DEV Community

loading...

LeetCode 35. Search Insert Position (javascript solution)

codingpineapple
・1 min read

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
};
Enter fullscreen mode Exit fullscreen mode

Discussion (0)