Leetcode Problem 35: Search Insert Position in Javascript

3/28/2024

Summary

A concise solution to LeetCode's Search Insert Position problem using linear search to find where a target value belongs in a sorted array, achieving excellent runtime performance.

Introduction

Hi everyone, today I tackled LeetCode problem 35: Search Insert Position. It’s a great practice problem for beginners like myself, even though it’s on the easier side. As usual, I’ll be solving it in JavaScript. Let’s dive in!

The problem explained

This problem asks you to find the correct insertion point for a given integer (`target`) within a sorted array (`nums`). The resulting array should maintain its sorted order.
Example:
Consider the array `nums = [1, 3, 5, 6]` and the target `target = 5`. The function should return `2` because inserting `5` at index 2 keeps the array sorted: `[1, 3, 5, 6]`.Key Points:- The array `nums` is always sorted in ascending order.- The target `target` might or might not already exist in the array.- If the target is larger than all elements in `nums`, it should be inserted at the end (index `nums.length`).

The solution

First idea

In my initial approach to this problem, I considered iterating through the nums array. If we encounter a value in nums[i] that’s greater than or equal to the target, we can break the loop and return that index as the insertion point.
var searchInsert = function(nums, target) {
for(let i=0; i<nums.length; i++){
if(nums[i] >= target){
return i
break
}
}
}
In my initial approach to this problem, I considered iterating through the nums array. If we encounter a value in nums[i] that’s greater than or equal to the target, we can break the loop and return that index as the insertion point.
return nums.length

The final code

So to test if it works we sumbit this final code:
var searchInsert = function(nums, target) {
for(let i=0; i<nums.length; i++){
if(nums[i] >= target){
return i
break
}
}
return nums.length
};
To verify its functionality, we submitted the final code. The feedback indicated success! The code boasts an impressive runtime of 44ms, outperforming 92.07% of other JavaScript submissions. Additionally, it utilizes a mere 49.2MB of memory, surpassing 22.54% of the competition.
If you have found a better solution, feel free to contact me and show it to me.

Final words

I hope you enjoyed reading this article.
If you have any questions or remarks feel free to contact me.
Your Mario 💚