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

1 Answer

0 votes
function findFirstSmallerNumberToTheLeft($arr) {
    $size = count($arr);
    for ($i = 0; $i < $size; $i++) {
        $first_smaller_number_to_the_left = -1; // if not found write -1
  
        for ($j = $i - 1; $j >= 0; $j--) {
            if ($arr[$j] < $arr[$i]) {
                $first_smaller_number_to_the_left = $arr[$j];
                break;
            }
        }
  
        echo $first_smaller_number_to_the_left . " ";
    }
}
  
$arr = array( 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
...