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

```.css-ds3kc{display:table-row;}.css-1t8atru{display:table-cell;opacity:0.5;padding-right:var(--chakra-space-6);-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;user-select:none;text-align:right;}1.css-2qghsv{display:table-cell;}/**2 * @param {number[]} nums3 * @param {number} target4 * @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 - 113      } else {14        left = mid + 115      }16      if (nums[mid] === target) {17        index = mid18      }19    }20
21    return index22  }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 + 129      } else {30        right = mid - 131      }32      if (nums[mid] === target) {33        index = mid34      }35    }36
37    return index38  }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}```

leetcode

array

binary search

## Next Post

LeetCode: Powerful Integers

May 1, 2021

Search Posts