Skip to main content

Find First and Last Position of Element in Sorted Array

Problem statement

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 = 8Output: [3,4]

Example 2:

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

Example 3:

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

Constraints:

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

My solution

/**
* @param {number[]} nums
* @param {number} target
* @return {number[]}
*/
var searchRange = function(nums, target) {
let i = 0;
let list = Array.from(new Array(2)).fill(-1);

if (nums.length === 1 && nums[0] === target) {
return [0, 0]
}
while(i < nums.length) {
if ((list[0] === -1 && nums[i] === target)) {
list[0] = i;
if (i === nums.length - 1) {
list[1] = i;
}
} else if (nums[i] === target && i === nums.length - 1) {
list[1] = i;
} else if(nums[i] !== target && nums[i - 1] === target) {
list[1] = i - 1;
}

i++;
}

// console.log(list);

return list;
};