LeetCode: Find First And Last Position Of Element In Sorted Array Solution

1/**
2 * @param {number[]} nums
3 * @param {number} target
4 * @return {number[]}
5 */
6var searchRange = function (nums, target) {
7 const binarySearchLeft = (nums, target) => {
8 let [left, right, index] = [0, nums.length - 1, -1]
9 while (left <= right) {
10 const mid = Math.floor((left + right) / 2)
11 if (nums[mid] >= target) {
12 right = mid - 1
13 } else {
14 left = mid + 1
15 }
16 if (nums[mid] === target) {
17 index = mid
18 }
19 }
20
21 return index
22 }
23 const binarySearchRight = (nums, target) => {
24 let [left, right, index] = [0, nums.length - 1, -1]
25 while (left <= right) {
26 const mid = Math.floor((left + right) / 2)
27 if (nums[mid] <= target) {
28 left = mid + 1
29 } else {
30 right = mid - 1
31 }
32 if (nums[mid] === target) {
33 index = mid
34 }
35 }
36
37 return index
38 }
39
40 return [binarySearchLeft(nums, target), binarySearchRight(nums, target)]
41}
42
43var searchRange = function (nums, target) {
44 return [nums.indexOf(target), nums.lastIndexOf(target)]
45}

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: Powerful Integers

HoningJS

Search Posts