DEV Community

Discussion on: Search Insert Position — JS (Day 9)

Collapse
peerreynders profile image
peerreynders • Edited on
  1. Seems a peculiar use of parseInt(string, radix). I would have expected Math.floor(number) or Math.trunc(number). parseInt converts the first argument (in this case a number) to a string before parsing it.

  2. Given that you chose to use parseInt(), not specifying the radix is risky. Basically in your case radix was undefined so JavaScript looks at the beginning of the first argument to figure out what radix to use. You lucked out but given that you know the radix you should use parseInt((start + end)/2, 10) instead (though I'm still voting for Math.floor(), Math.trunc()).

const values = [1, 3, 5, 6];
const empty = [];

console.log(searchInsert(values, 5)); // 2
console.log(searchInsert(values, 2)); // 1
console.log(searchInsert(values, 7)); // 4
console.log(searchInsert(empty, 7)); // 0

function searchInsert(values, target) {
  let low = 0;
  let high = values.length;
  while (low < high) {
    const mid = Math.trunc((low + high) / 2);
    if (values[mid] > target) {
      high = mid;
    } else {
      low = mid + 1;
    }
  }
  const i = high - 1;
  return i > -1 && values[i] === target ? i : high;
}
Enter fullscreen mode Exit fullscreen mode
Collapse
tanvirrahman profile image
Tanvir Rahman Author

Looks great. Thanks for your suggestion…