Menu

Sign in to track your progress and unlock all features.

Theme style

Start learning freeLog in

Problem No 24

Generate Pascal's Triangle

Hard

24 minute session

Summary

Produce the first n rows of Pascal's triangle using loops.

Problem statement

Write pascals_triangle(n) that returns a list of lists representing the first n rows (top to bottom) of Pascal's triangle. Each row is a list of integers. Rules: - Row 1 is [1]. - Each element inside a row (not on edges) is the sum of the two elements above it from the previous row. - If n is 0, return an empty list. Use loops to build rows iteratively. Aim for clarity and correctness for n up to at least 20.

Task

Implement a function to generate Pascal's triangle rows iteratively without using recursion or external libraries.

Examples

First 5 rows

Input

pascals_triangle(5)

Output

[[1], [1, 1], [1, 2, 1], [1, 3, 3, 1], [1, 4, 6, 4, 1]]

Explanation

Each row is built from the previous row by summing adjacent pairs and adding 1s at the ends.

Input format

A single integer n (number of rows).

Output format

A list of n lists, each inner list is a row of integers from Pascal's triangle.

Constraints

0 <= n <= 20. Time complexity O(n^2) is acceptable. Use loops (for/while) to build the triangle.

Samples

Sample input 0

pascals_triangle(3)

Sample output 0

[[1], [1, 1], [1, 2, 1]]

Explanation 0

Three rows starting from [1].

Code editor
Loading editor…

AI assistant

Ask me anything!

Need help? I can explain the core idea behind this problem, review your current code, and give targeted hints. Use “Teach Theory” for the concept, “Get AI hint” for a quick scaffold nudge, or ask a specific question below.

Chat history is temporary and will not be saved.

Free preview includes 1 Teach Theory response and 1 AI hint per unlocked preview lesson.