Leetcode Problem 35: Search Insert Position in Javascript

Mario Raach
2 min readMar 27, 2024

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.

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.

The final code

So to test if it works we sumbit this final code:

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 💚

--

--