DEV Community

ZeeshanAli-0704
ZeeshanAli-0704

Posted on • Edited on

Find First and Last Position of Element in Sorted Array

Find First and Last Position of Element in Sorted Array

/**
 * @param {number[]} nums
 * @param {number} target
 * @return {number[]}
 */
var searchRange = function (nums, target) {
  const firstOcurance = searchFirstOccurance(nums, target);
  const lastOcurrance = searchLastOccurance(nums, target);
  if (firstOcurance === -1) {
    return [-1, -1];
  } else {
    return [firstOcurance, lastOcurrance];
  }
};

var searchFirstOccurance = function (nums, target) {
  let high = nums.length - 1;
  let low = 0;

  while (low <= high) {
    let mid = parseInt((low + high) / 2);

    if (nums[mid] > target) {
      high = mid - 1;
    } else if (nums[mid] < target) {
      low = mid + 1;
    } else {
      if (mid === 0 || nums[mid - 1] !== nums[mid]) {
        return mid;
      } else {
        high = mid - 1;
      }
    }
  }

  return -1;
};
var searchLastOccurance = function (nums, target) {
  let high = nums.length - 1;
  let low = 0;

  while (low <= high) {
    let mid = parseInt((low + high) / 2);

    if (nums[mid] > target) {
      high = mid - 1;
    } else if (nums[mid] < target) {
      low = mid + 1;
    } else {
      if (mid === nums.length - 1 || nums[mid] !== nums[mid + 1]) {
        return mid;
      } else {
        low = mid + 1;
      }
    }
  }

  return -1;
};

console.log(searchRange([5, 7, 7, 8, 8, 10], 8));

Enter fullscreen mode Exit fullscreen mode

Top comments (2)

Collapse
 
frankwisniewski profile image
Frank Wisniewski

indexOf and lastIndexOf ??

Collapse
 
zeeshanali0704 profile image
ZeeshanAli-0704 • Edited

Yes, but this question is of type Binary Search algo... & it gives condition of not using the defined methods..

leetcode.com/problems/find-first-a...