How to find first and last positions of an element in a sorted array in Node.js

1 Answer

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

 



answered 5 days ago by avibootz
...