Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Prodentim Probiotics Specially Designed For The Health Of Your Teeth And Gums

Instant Grammar Checker - Correct all grammar errors and enhance your writing

Teach Your Child To Read

Powerful WordPress hosting for WordPress professionals

Disclosure: My content contains affiliate links.

31,038 questions

40,790 answers

573 users

How to find the previous smaller element from the beginning of array for each array element in TypeScript

1 Answer

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

    

 





answered Nov 25, 2021 by avibootz
...