DEV Community

Kevin Coto🚀💡
Kevin Coto🚀💡

Posted on • Edited on

Yeah Leetcode without Google or LLM Part 1 (35. Search Insert Position)

The problem is here

My Solution:

/**
 * @param {number[]} nums
 * @param {number} target
 * @return {number}
 */
var searchInsert = function(nums, target) {
    for(let i = 0; i < nums.length; i++){
        if(nums[i]==target) return i
        if (nums[i] < target && 
        (i + 1 === nums.length || target < nums[i + 1])) {
return i + 1;
}

    }
return 0
};
Enter fullscreen mode Exit fullscreen mode

My path of thinking:

  1. Place a guard in case the first element is equal to the target.
  2. Check if the nums[i] is less than target return i(works for few cases
  3. Check also if the the following index in the array is bigger than target so we can place target in the middle
  4. In some cases there's not following index, check with i+1===nums.length if we are going out of bound
  5. In default case where target is the lowest just return 0

Conclusion:

It's slow, really slow. We should be doing Binary Search something that I've used in the past yes but it doesn't come natural.

Takeaway: Study and apply Binary Search
For more look into thekoto.dev/blog

Top comments (0)