LeetCode: Search Insert Position Solution

Understand why returns "low/left"

Approach

Goal of this problem is understanding classic binary search pattern in a different way: why returns low/left?

Implementation

1/**
2 * @param {number[]} nums
3 * @param {number} target
4 * @return {number}
5 */
6var searchInsert = function (nums, target) {
7 let N = nums.length
8 let left = 0
9 let right = N - 1
10 let res = null
11
12 while (left <= right) {
13 let mid = Math.floor((left + right) / 2)
14 if (nums[mid] > target) {
15 right = mid - 1
16 } else if (nums[mid] < target) {
17 left = mid + 1
18 } else {
19 res = mid
20 break
21 }
22 }
23
24 return res !== null ? res : left
25}

Comments

Loading comments...

Tags

leetcode

array

binary search

Apply and earn a $2,500 bonus once you're hired on your first job!

Clients from the Fortune 500 to Silicon Valley startups

Choose your own rate, get paid on time

From hourly, part-time, to full-time positions

Flexible remote working environment

A lot of open JavaScript jobs!!

Fact corner: Referred talent are 5x more likely to pass the Toptal screening process than the average applicant.

Still hesitate? Read HoningJS author's guide on dealing with Toptal interview process.

Next Post

LeetCode: Linked List Cycle II

Same as LC 141, but different in return

Previous Post

LeetCode: Design Linked List

Implement some linked list methods

HoningJS

Search Posts