How to find first and last positions of an element in a sorted array in TypeScript

1 Answer

0 votes
function find_first_and_Last_position(arr: number[], n: number): number[] { 
    let first: number = -1;
    let last: number = -1; 
       
    for (let i: number = 0; i < arr.length; i++) { 
        if (n != arr[i]) 
            continue; 
        if (first == -1) 
            first = i; 
        last = i; 
    } 
  
    return [first, last];
} 
 
  
const arr: number[] = [1, 3, 7, 8, 3, 1, 9]; 
const n: number = 3; 
       
const result: number[] = find_first_and_Last_position(arr, n); 
   
const first: number = result[0];
const last: number = result[1];
   
if (first != -1) {
    console.log("First positions = " + first + " Last positions = " + last); 
}
else {
    console.log("Not found\n"); 
}
 


/*
run:
  
"First positions = 1 Last positions = 4" 
  
*/

 



answered 5 days ago by avibootz
...