LeetCode problem #35 — Search Insert Position (JavaScript)

Solution #1: The for loop

The brute-force approach here is to do more or less exactly what is described above. We loop through the array’s values, looking for the target. If we find either the target, or the first occurrence of an integer higher than the target one (which indicates that that’s where the target would be located), we return the index.

Solution #2: Binary search

To speed things up, we can employ the use of a fairly standard binary search. The search will half the available array, look for which side’s range of values contains the target (or integers higher than it), and then discards the other side, before repeating the process. This means we keep cutting down the array, checking as little data as possible each time, until we’re left either with the target integer, or the next highest number from it, giving us our answer.



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

Duncan McArdle


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