Pascal's triangle II


Solution

  • Solution is simple and very unefficient. Task is basically the first part. Probably requires to come up with some formula that would allow avoiding the all rows calculation. I am about to discover other solutions that have better space and memory efficiency.
function getRow(rowIndex: number): number[] {
    const result = [[1]];

    for(let i = 1; i <= rowIndex; i++){
        const prev = result[i - 1];
        const next = [];
        for(let j = 0; j <= prev.length; j++){
            const left = prev[j - 1] ?? 0;
            const right = prev[j] ?? 0;
            next[j] = left + right;
        }
        result.push(next);
    }

    return result[rowIndex]
};

Performance

  • Algorithm has O(n^2) time complexity (very bad)
  • Runtime beats only 5.6% percent of other solutions