Leetcode #118: Pascal's Triangle
In this guide, we solve Leetcode #118 Pascal's Triangle in Python and focus on the core idea that makes the solution efficient.
You will see the intuition, the step-by-step method, and a clean Python implementation you can use in interviews.

Problem Statement
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: Example 1: Input: numRows = 5 Output: [[1],[1,1],[1,2,1],[1,3,3,1],[1,4,6,4,1]] Example 2: Input: numRows = 1 Output: [[1]] Constraints: 1 <= numRows <= 30
Quick Facts
- Difficulty: Easy
- Premium: No
- Tags: Array, Dynamic Programming
Intuition
The problem breaks into overlapping subproblems, so caching results prevents exponential repetition.
A carefully chosen DP state captures exactly what we need to build the final answer.
Approach
Define the DP state and recurrence, then compute states in the correct order.
Optionally compress space once the recurrence is clear.
Steps:
- Choose a DP state definition.
- Write the recurrence and base cases.
- Compute states in the correct order.
Example
Input: numRows = 5
Output: [[1],[1,1],[1,2,1],[1,3,3,1],[1,4,6,4,1]]
Python Solution
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
The time complexity is , where is the given number of rows. The space complexity is .
Edge Cases and Pitfalls
Watch for boundary values, empty inputs, and duplicate values where applicable. If the problem involves ordering or constraints, confirm the invariant is preserved at every step.
Summary
This Python solution focuses on the essential structure of the problem and keeps the implementation interview-friendly while meeting the constraints.