Anjan Dutta

Leet Code 35: Search Insert Position

Leet Code 35: Search Insert Position

Problem statement:

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.

Constraints:

  • 1 <= nums.length <= 104
  • -104 <= nums[i] <= 104
  • nums contains distinct values sorted in ascending order.
  • -104 <= target <= 104

Solution:

/**

  • @param {number[]} nums
  • @param {number} target
  • @return {number} */ var searchInsert = function(nums, target) {
    let s = 0;
    let e = nums.length - 1;
    while (s <= e) {
    const m = Math.floor((s + e)/2);
    if(nums[m]=== target) {
    return m;
    } else if(nums[m]<target) {
    s = m+1;
    } else {
    e = m-1;
    }
    }
    return s;

};