EasyNo. 0118

Pascal's Triangle — LeetCode 118 Python Solution

Topics
Array, Dynamic Programming
Reading time
2 min

The problem

Given an integer numRows, return the first numRows of 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
numRows = 5
Output
[[1],[1,1],[1,2,1],[1,3,3,1],[1,4,6,4,1]]

Python solution

PythonSolution
class Solution:
    def generate(self, numRows: int) -> List[List[int]]:
        f = [[1]]
        for i in range(numRows - 1):
            g = [1] + [a + b for a, b in pairwise(f[-1])] + [1]
            f.append(g)
        return f

Complexity

Time
O(n2)where n is the given number of rows
Space · auxiliary
O(1)

Pattern: Dynamic Programming

Define a state, write the transition, and stop recomputing the same subproblem. LeetCode 118. Pascal's Triangle 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 118. Pascal's Triangle?

LeetCode 118. Pascal's Triangle is rated Easy on LeetCode.

What is the time complexity of LeetCode 118. Pascal's Triangle?

The Python solution on this page runs in O(n2), where n is the given number of rows.

What is the space complexity of LeetCode 118. Pascal's Triangle?

The Python solution on this page uses O(1) auxiliary space.

What topics does LeetCode 118. Pascal's Triangle cover?

LeetCode 118. Pascal's Triangle 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.

Free to download. Check it runs on your machine, then pick a plan.