Last updated: Nov 27, 2022
Difficulty : medium
Runtime : 85 ms Faster than 73.21 %
Memory : 42.6 mb Lesser than 60.56 %

# 34. Find First and Last Position of Element in Sorted Array

Given an array of integers nums sorted in non-decreasing order, find the starting and ending position of a given target value.

If target is not found in the array, return [-1, -1].

You must write an algorithm with O(log n) runtime complexity.

Example 1: Input: nums = [5,7,7,8,8,10], target = 8 Output: [3,4]

Example 2: Input: nums = [5,7,7,8,8,10], target = 6 Output: [-1,-1]

Example 3: Input: nums = [], target = 0 Output: [-1,-1]

Constraints:

• 0 <= nums.length <= 105
• -109 <= nums[i] <= 109
• nums is a non-decreasing array.
• -109 <= target <= 109

## Solution:

``````/**
* @param {number[]} nums
* @param {number} target
* @return {number[]}
*/
var searchRange = function(nums, target) {
if (nums.length === 1 && nums[0] === target) return [0, 0];
if (nums.length === 0) return [-1, -1];

var l = 0;
var r = nums.length - 1;
var foundStart = -1;
var foundEnd = -1;

while (l <= r) {
if (nums[l] === target && foundStart === -1) {
foundStart = l;

if (nums[r] === nums[foundStart]) {
foundEnd = r;
break;
}
} else if (foundStart !== -1) {
var m = ((l + r) / 2) ^ 0;
if (target > nums[m]) {
l = m + 1;
} else if (target < nums[m]) {
r = m - 1;
} else if (target === nums[m]) {
foundEnd = m;
l = m + 1;
} else l++;
} else l++;
}

if (foundStart !== -1 && foundEnd === -1) foundEnd = foundStart;
return [foundStart, foundEnd];
};
``````