Skip to content

Instantly share code, notes, and snippets.

@Ephraimiyanda
Created January 23, 2026 23:22
Show Gist options
  • Select an option

  • Save Ephraimiyanda/571cae214712fed23f883cfd564bc648 to your computer and use it in GitHub Desktop.

Select an option

Save Ephraimiyanda/571cae214712fed23f883cfd564bc648 to your computer and use it in GitHub Desktop.
Find First and Last Position of Element in Sorted Array

Question

Approach

  1. the numbers are looped through to check for numbers that are the target.
  2. the index of the numbers are then added to an array.
  3. since we are looking for the range , the minimum and max value of the indexes are returned

Complexity

  • Time complexity:O(N)

  • Space complexity:O(N)

Code

function searchRange(nums: number[], target: number): number[] {
    let positions = []
    for (let i = 0; i < nums.length; i++) {
        if (nums[i] === target) {
            positions.push(i)
        }

    }
    if (positions.length === 0) positions.push(-1, -1)
    return [Math.min(...positions),Math.max(...positions)]
};
scrnli_QSpYBAl1Si9Rn1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment