Find First and Last Position of Element in Sorted Array in TypeScript

function searchRange(nums: number[], target: number): number[] {
    // binarySearchLeft: A modified binary search function to find the leftmost index of the target.
    function binarySearchLeft(nums: number[], target: number): number {
        let left: number = 0, right: number = nums.length - 1;
        while (left <= right) {
            // Calculate the middle index of the current search range.
            let mid: number = left + Math.floor((right - left) / 2);

            // Narrow down the search to the left half if the target is less than or equal to the middle element.
            if (nums[mid] < target) {
                left = mid + 1;
            } else {
                right = mid - 1;
            }
        }
        // Return the left boundary which points to the first occurrence of the target.
        return left;
    }

    // binarySearchRight: A modified binary search function to find the rightmost index of the target.
    function binarySearchRight(nums: number[], target: number): number {
        let left: number = 0, right: number = nums.length - 1;
        while (left <= right) {
            // Calculate the middle index of the current search range.
            let mid: number = left + Math.floor((right - left) / 2);

            // Narrow down the search to the right half if the target is greater than the middle element.
            if (nums[mid] <= target) {
                left = mid + 1;
            } else {
                right = mid - 1;
            }
        }
        // Return the right boundary which points to the last occurrence of the target.
        return right;
    }

    // Use the binary search functions to find the first and last positions of the target.
    let first: number = binarySearchLeft(nums, target);
    let last: number = binarySearchRight(nums, target);

    // Check if the target is present in the array.
    // If first is less than or equal to last, the target is present, and we return the indices.
    // Otherwise, return [-1, -1] indicating the target is not present.
    if (first <= last) {
        return [first, last];
    }
    return [-1, -1];
}

PrevNext