LeetCode problem #35 — Search Insert Position (JavaScript)

In this LeetCode problem, we’re given an array of ordered integers, and a target integer, and asked to return the index of where the target can be found in the array. If the target cannot be found in the array, we’re asked to return the index of where it would be found if it were added.

The basic idea behind solving this problem is to look for the first occurrence in the array that is greater than or equal to the target number. So that’s what we’ll do below, in two different ways.

Solution #1: The for loop

The downside of this simple solution is that we have to check every number in the array in order to get our answer.

Solution #2: Binary search

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Duncan McArdle

Full-stack software developer from the UK, author of the Aftermath book series, full time tech-nerd.