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

202409292212
tags: #binary-search

var searchRange = function(nums, target) {
	const find = (findFirstIndex) => {
		let start = 0;
		let end = nums.length - 1;
		let pos = -1;
		while (start <= end) {
			const mid = Math.floor((end - start) / 2) + start;
			if (nums[mid] === target) {
				pos = mid;
				if (findFirstIndex) {
					end = mid - 1;
				} else {
					start = mid + 1;
				}
			}
			else if (nums[mid] < target) {
				start = mid + 1;
			} else {
				end = mid - 1;
			}
		}
		return pos;
	}
	
	return [find(true), find(false)];
};

Reference

https://leetcode.com/problems/find-first-and-last-position-of-element-in-sorted-array/