Last updated on July 13, 2024
Algorithm: Two Pointers
Once again another problem that can be solved fairly easily via using Two Pointers. Prior to learning this approach the naive approach might have led to some gnarly nested code. The main objective was to write an algorithm with O(log n) runtime. Here is a link to the problem if you’d like to try it out: https://leetcode.com/problems/search-insert-position/.
Here is my solution, it could be optimized though this was my accepted solution with good enough performance:
/**
* @param {number[]} nums
* @param {number} target
* @return {number}
*/
var searchInsert = function (nums, target) {
let left = 0,
right = nums.length - 1;
if (nums[right] < target) {
return nums.length;
} else if (nums[left] > target) {
return 0;
}
if (nums.includes(target)) {
return nums.indexOf(target);
} else {
while (left <= right) {
if (left === right) {
return left;
}
if (nums[left] < target) {
left++;
} else if (nums[right] > target) {
right--;
} else if (nums[left] === target) {
return left;
} else if (nums[right] === target) {
return right;
}
}
}
};