Pascal's Triangle II — LeetCode 119 Python Solution

EasyArrayDynamic Programming
Problem
#119
Reading time
2 min

The problem

Given an integer rowIndex, return the rowIndexth (0-indexed) row of the Pascal's triangle. In Pascal's triangle, each number is the sum of the two numbers directly above it as shown:

This statement is abridged. Read the full problem on LeetCode.

Example

Input
rowIndex = 3
Output
[1,3,3,1]

Python solution

Python
class Solution:
    def getRow(self, rowIndex: int) -> List[int]:
        f = [1] * (rowIndex + 1)
        for i in range(2, rowIndex + 1):
            for j in range(i - 1, 0, -1):
                f[j] += f[j - 1]
        return f

Complexity

MeasureComplexity
TimeO(n^2)
SpaceO(n) auxiliary

Pattern: Dynamic Programming

Define a state, write the transition, and stop recomputing the same subproblem. LeetCode 119. Pascal's Triangle II is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Dynamic Programming.

The dynamic programming guide has the Python template for the pattern and the 481 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 119. Pascal's Triangle II?
LeetCode 119. Pascal's Triangle II is rated Easy on LeetCode.
What is the time complexity of LeetCode 119. Pascal's Triangle II?
The Python solution on this page runs in O(n^2).
What is the space complexity of LeetCode 119. Pascal's Triangle II?
The Python solution on this page uses O(n) auxiliary space.
What topics does LeetCode 119. Pascal's Triangle II cover?
LeetCode 119. Pascal's Triangle II is tagged Array and Dynamic Programming on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview