How to find the first smaller number to the left element for each array element in JavaScript

1 Answer

0 votes
function findFirstSmallerNumberToTheLeft(arr) {
	const size = arr.length;
    let s = "";
    for (let i = 0; i < size; i++) {
        let first_smaller_number_to_the_left = -1; // if not found write -1
  
        for (let j = i - 1; j >= 0; j--) {
            if (arr[j] < arr[i]) {
                first_smaller_number_to_the_left = arr[j];
                break;
            }
        }
        s += first_smaller_number_to_the_left + " ";
    }
    console.log(s);
}
  
const arr = [ 2, 6, 3, 7, 8, 1, 9, 0, 13, 19, 18 ];
     
// 2:-1 // 6:2 // 3:2 // 7:3 // 8:7 // 1:-1 // 9:1 // 0:-1 // 13:0 // 19:13 // 18:13
  
findFirstSmallerNumberToTheLeft(arr);




/*
run:

"-1 2 2 3 7 -1 1 -1 0 13 13 "

*/

 



answered Nov 25, 2021 by avibootz
...