Triangle Rule
Edges & neighbors
Every row starts and ends with 1; each inner value is the sum of the two numbers above it.
Pascal’s triangle is a classic interview warm-up: nested loops, binomial coefficients, and clean printing. This tutorial covers the triangle rule, two generation methods, a live preview, algorithm steps, worked Python examples, edge cases, and complexity.
Edges & neighbors
Every row starts and ends with 1; each inner value is the sum of the two numbers above it.
n choose k
Entry at row i, column j equals the binomial coefficient C(i, j).
In-row update
Update coeff = coeff * (i - j) // (j + 1) to walk a row without factorials.
Prev-row sums
Build each row from the previous list by adding adjacent neighbors.
1–14 rows
Pick a row count and draw a centered triangle instantly in the browser.
Complexity
Both methods print r rows in quadratic time; space differs by approach.
Pascal’s triangle starts with a single 1 at the top. Every row begins and ends with 1, and each middle value is the sum of the two numbers directly above it.
In code interviews you are usually asked to print the first r rows with spacing so the triangle looks centered. You can compute values with a multiplicative binomial update, or build each row from the previous one using neighbor sums.
It trains nested loops, careful indexing, and combinatorics without needing a factorial helper. The same numbers power binomial expansions and many DP warm-ups.
Row i has i + 1 entries (0-based), always edged with 1.
Position (i, j) is C(i, j) — useful beyond printing.
Multiplicative, additive, or return a nested list.
Values grow fast; Python ints do not overflow like C int.
In short: print r rows of Pascal’s triangle — edges are 1, insides are neighbor sums (or binomial updates) — and format spacing so the shape reads as a triangle.
Given a positive integer rows, print the first rows levels of Pascal’s triangle.
# First 5 rows (conceptual shape)
# 1
# 1 1
# 1 2 1
# 1 3 3 1
# 1 4 6 4 1 | Item | Type | Description |
|---|---|---|
rows | int | Number of triangle rows to print (must be ≥ 1 for a visible triangle). |
| Printed output | text | Centered rows of integers with fixed-width spacing. |
for i from 0 to rows - 1:
print leading spaces
coeff = 1
for j from 0 to i:
print coeff
coeff = coeff * (i - j) / (j + 1) | Method | Idea | Extra space |
|---|---|---|
| Multiplicative | Update binomial coefficient along the row | O(1) |
| Additive | Sum neighbors from the previous row list | O(rows) |
| Goal | Pattern |
|---|---|
| Next binomial in a row | coeff = coeff * (i - j) // (j + 1) |
| Inner cell from previous row | cur[j] = prev[j - 1] + prev[j] |
| Leading spaces | print(" " * (rows - i - 1), end="") |
| Fixed-width number | print(f"{coefficient:6d}", end="") |
| Row length | Row i has i + 1 values (0-based) |
All can print the triangle — but clarity and cost differ.
in-row updateNo factorial calls; compact and O(1) extra space
prev + prevMatches the geometric definition; keeps a previous row
factorialsWorks but slower and easier to get wrong for beginners
explain bothKnow the rule first, then pick a clean implementation
Reach for Pascal’s triangle drills when nested loops and binomial thinking matter.
Quick check of loops, indexing, and formatted output.
Connect printed numbers to C(n, k) without heavy math libraries.
Additive rows resemble filling a DP table from previous states.
Outer row loop + inner column loop with a clear visual result.
Deep triangles explode in size — cap previews and discuss big integers.
Key benefit: one visual problem that covers loops, math, formatting, and complexity in a short exercise.
Choose a row count between 1 and 14 and draw the triangle in the browser.
Three complete Python programs — multiplicative update, additive row construction, and a return-a-list variant. Click View Output to reveal sample console results.
Print five rows with clean spacing.
Classic direct coefficient generation for each row — no factorial helper required.
def generate_pascals_triangle(rows: int) -> None:
for i in range(rows):
coefficient = 1
for _ in range(rows - i - 1):
print(" ", end="")
for j in range(i + 1):
print(f"{coefficient:6d}", end="")
coefficient = coefficient * (i - j) // (j + 1)
print()
generate_pascals_triangle(5) Each row starts with coefficient = 1. After printing a value, the next coefficient is updated with coeff * (i - j) // (j + 1), which stays exact for binomial rows. Leading spaces keep the triangle centered.
Build rows from the geometric definition.
Directly follows the sum-of-two-above definition using lists.
def generate_pascals_triangle_additive(rows: int) -> None:
prev: list[int] = []
for i in range(rows):
cur = [1] * (i + 1)
for j in range(1, i):
cur[j] = prev[j - 1] + prev[j]
for _ in range(rows - i - 1):
print(" ", end="")
for val in cur:
print(f"{val:6d}", end="")
print()
prev = cur
generate_pascals_triangle_additive(5) Seed cur as all ones, then overwrite middle cells with prev[j - 1] + prev[j]. Edges stay 1 automatically. Store prev = cur for the next iteration.
Many prompts ask for list[list[int]] instead of printing.
Build and return the triangle as nested lists — the common LeetCode-style signature.
def generate(num_rows: int) -> list[list[int]]:
if num_rows < 1:
return []
triangle: list[list[int]] = []
for i in range(num_rows):
row = [1] * (i + 1)
for j in range(1, i):
row[j] = triangle[i - 1][j - 1] + triangle[i - 1][j]
triangle.append(row)
return triangle
print(generate(5)) Same additive rule as Example 2, but each finished row is appended to triangle. Returning data is usually what automated judges expect; printing is for console demos.
For row i from 0 to rows - 1, print leading spaces first.
Either update the coefficient formula or sum neighbors from the previous row.
Output numbers with fixed-width fields, then a newline.
After the last row, the centered Pascal triangle is fully printed.
i = 4Trace the multiplicative update for the fifth printed row (0-based i = 4). Start with coeff = 1, then apply coeff = coeff * (i - j) // (j + 1) after each print.
j | Update after print | Next coeff | |
|---|---|---|---|
0 | 1 | 1 * (4 - 0) // (0 + 1) | 4 |
1 | 4 | 4 * (4 - 1) // (1 + 1) | 6 |
2 | 6 | 6 * (4 - 2) // (2 + 1) | 4 |
3 | 4 | 4 * (4 - 3) // (3 + 1) | 1 |
4 | 1 | (row ends) | — |
Printed row: 1 4 6 4 1 — exactly C(4, 0) … C(4, 4).
Where Pascal’s triangle (and its rows) show up beyond the interview prompt.
Read “n choose k” values without writing a factorial helper.
Example: C(5, 2) = 10 from row 5.
Coefficients of (a + b)n are exactly row n.
Example: (a+b)³ → 1, 3, 3, 1.
Builds intuition for tabulation from previous states.
Example: each cell depends on two parents above.
Nested loops plus formatting practice for beginners.
Example: centered print with fixed-width fields.
Binomial probabilities reuse the same coefficients.
Example: fair-coin paths of length n.
Shows why off-by-one bugs appear at triangle edges.
Example: middle loop runs only for 1..i-1.
Pro Tip: if the interviewer asks for a 2D list, return rows; if they ask to “print the triangle,” prioritize readable spacing after correct values.
Why these two generation styles earn interview points.
Computes a full row with O(1) extra memory and no previous-row storage.
Neighbor sums are easy to explain on a whiteboard from the geometric rule.
Avoids huge intermediate products from computing n! / (k!(n-k)!) directly.
The multiplicative step stays on integers when you use // correctly.
Pro Tip: lead with the additive story for clarity, then mention the multiplicative update as the space-leaner variant.
Small habits that keep Pascal code clean in interviews.
Ask whether the judge wants console output or a nested list before writing formatting code.
Initialize rows as all 1s, then fill only middle indices — fewer off-by-one bugs.
// Over /Float division can introduce rounding risk; integer division matches the math.
Decide whether row 0 or row 1 is the top, and stick to that in comments and loops.
Get values right first; spacing is polish for human-readable demos.
Pro Tip: dry-run one small row on paper (like i = 4 above) before coding — it catches formula mistakes fast.
Mistakes that commonly break Pascal triangle solutions.
/ Instead of //Float division can yield non-integers and wrong later coefficients.
→ Always use integer division for the multiplicative update.
Filling range(i) or range(i + 1) overwrites edges or skips cells.
→ For additive rows, update only range(1, i).
Editing prev while reading it corrupts neighbor sums.
→ Build a new cur list each iteration (or copy carefully).
Computing C(n, k) via full factorials is slower and messier than needed.
→ Prefer multiplicative or additive construction.
rows ≤ 0 should return empty / error per the prompt — not crash mid-loop.
→ Validate early; for list APIs, return [].
Check these inputs before calling the solution done.
Output is just 1 (or [[1]] for list APIs).
Return [] or print nothing — match the problem statement.
rows < 0Treat as invalid; raise or return empty depending on requirements.
Python ints stay exact; watch print width and time for very large r.
Confirm whether “n rows” means indices 0..n-1 or 1..n.
Large numbers overflow %6d-style fields — widen or skip centering.
Handy facts interviewers sometimes ask as follow-ups.
n (0-based) is 2n.n is the coefficient list for (a + b)n.Try these variations to lock in the pattern.
nlist[list[int]]num_rows in {0, 1, 5}sum(row) == 2 ** i for each generated row// is correct for the multiplicative update — each step is exact.rows > 0 before printing; rows = 1 should print a single 1.Quick Takeaway: edges are 1, insides are neighbor sums (or binomial updates), and printing r rows costs O(r²).
| Program | Time | Extra space |
|---|---|---|
| Multiplicative method | O(rows²) | O(1) |
| Additive row method | O(rows²) | O(rows) |
| Return list of lists | O(rows²) | O(rows²) (stores all cells) |
Pascal’s triangle is a small nested-loop exercise with big teaching payoff: binomial coefficients, careful indexing, and readable output. Master both the multiplicative update and the additive prev-row approach so you can explain either in an interview.
Practice the three examples above, then continue to perfect numbers for another classic number-theory check.
Edges are 1, insides are neighbor sums — keep the formula exact with //, and validate row counts before printing.
// for multiplicative binomial updatesrows ≥ 1 (or handle empty output explicitly)rows = 1 edge casePrint rows the interview-friendly way.
Edges 1, insides sum
DefinitionC(i, j) at cell
MathIn-row coeff update
CodePrev-row neighbors
CodeO(r²) time
AnalysisEach entry in Pascal’s triangle is a binomial coefficient “n choose k”, which also appears in (a + b)n expansion.
Learn how to check whether a number equals the sum of its proper divisors.
8 people found this page helpful