Technical Interview Question – Pascal’s Triangle

Here is more complicated question which is sometimes asked during a technical interview.

Write a function that prints out the first n rows of Pascal’s triangle (with f(1) yielding the row consisting of only the element 1). This can be done either by summing elements from the previous rows or using a binary coefficient or combination function. Behavior for n <= 0 does not need to be uniform, but should be noted.

Pascal’s triangle is an arithmetic and geometric figure first imagined by Blaise Pascal. Its first few rows look like this:

   1
  1 1
 1 2 1
1 3 3 1

Each element of each row is either 1 or the sum of the two elements right above it. For example, the next row would be 1 (since the first element of each row doesn’t have two elements above it), 4 (1 + 3), 6 (3 + 3), 4 (3 + 1), and 1 (since the last element of each row doesn’t have two elements above it). Each row n (starting with row 0 at the top) shows the coefficients of the binomial expansion of (x + y)n.

function pascalsTriangle($num)
{
    $c = 1;
    $triangle = Array();

    for($i=0;$i<=$num;$i++) {
        $triangle[$i] = Array();
        if(!isset($triangle[$i-1])) {
            $triangle[$i][] = $c;
        }
        else{
            for($j=0; $j < count($triangle[$i-1])+1; $j++){
                if (isset($triangle[$i-1][$j-1]) && isset($triangle[$i-1][$j])) {
                    $triangle[$i][] = $triangle[$i-1][$j-1] + $triangle[$i-1][$j] 
                }
                else {
                    $triangle[$i][] = $c;
                }
            }
        }
    }

    return $triangle;
}
 
$tria = pascalsTriangle(8);
foreach($tria as $val) {
    foreach($val as $value) {
        echo $value . ' ';
    }
    echo '
'; }