How to find the nearest smaller element on left side of each element of an array in Node.js

1 Answer

0 votes
function smaller_index(arr, pos) {
    let index = -1;
        
    for (let i = pos - 1; i >= 0 && index == -1; i--) {
         if (arr[i] < arr[pos]) {
             index = i;
         }
    }
    return index;
}
function nearest_smaller(arr) {
    let index = 0, size = arr.length;
           
    for (let i = 0; i < size; i++) {
        index = smaller_index(arr, i);
        
        if (index == -1) {
            console.log(arr[i] + " : No Smaller");
        }
        else {
               console.log(arr[i] + " : " + arr[index]);
            }
        }
    }
        
        
 const arr = [4, 6, 2, 8, 6, 1, 9, 12, 3, 20, 18, 30];

 nearest_smaller(arr);
   
   
   
   
/*
run:
    
4 : No Smaller
6 : 4
2 : No Smaller
8 : 2
6 : 2
1 : No Smaller
9 : 1
12 : 9
3 : 1
20 : 3
18 : 3
30 : 18
    
*/

 



answered Dec 20, 2021 by avibootz
...