Code-golf generate pascal's triangle
Master System Design with Codemia
Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.
Introduction
Pascal's Triangle is a triangular array where each number is the sum of the two numbers directly above it. The first and last elements of every row are 1. It encodes binomial coefficients — row n, position k equals C(n,k). In code-golf, the challenge is to generate it in the fewest characters. Beyond golf, understanding the algorithm is useful because Pascal's Triangle appears in combinatorics, probability, polynomial expansion, and fractal patterns.
The Triangle
Each interior value is the sum of the two values above it: triangle[n][k] = triangle[n-1][k-1] + triangle[n-1][k].
Python: Standard Implementation
This builds each row by summing adjacent pairs from the previous row and adding 1s at both ends.
Python: Code-Golf Solutions
The zip([0]+r, r+[0]) trick pads the row with zeros on each side, so summing pairs naturally produces the next row including the boundary 1s.
JavaScript Solutions
Using Math (Binomial Coefficients)
math.comb(n, k) directly computes binomial coefficients. This is clean but slower than the iterative approach for large triangles because each comb call is independent.
Recursive Approach
The recursive version builds the triangle top-down. It is elegant but hits Python's recursion limit for large n (default 1000).
Applications of Pascal's Triangle
Pretty Printing
Common Pitfalls
- Off-by-one in row count: Some implementations count rows starting from 0 (row 0 = [1]), others from 1. Clarify whether
nmeans "n rows" or "rows 0 through n" to avoid generating one too many or too few rows. - Not handling n=0: An empty triangle (0 rows) should return an empty list, not
[[1]]. Always handle the edge case where no rows are requested. - Integer overflow in other languages: Pascal's Triangle values grow as
C(n, n/2), which reaches billions by row 34. In C/C++ or Java, uselongorBigIntegerfor rows beyond 30. - Modifying the previous row in place: When building a new row from the previous one, modifying the previous row during iteration produces incorrect results. Always read from the old row and write to a new one.
- zip() truncating to shorter list: In
zip([0]+r, r+[0]), both lists have the same length. But if you mistakenly usezip(r, r[1:]), the result is one element shorter than needed, missing the trailing 1.
Summary
- Pascal's Triangle row
ncontains binomial coefficientsC(n, 0)throughC(n, n) - Build each row by summing adjacent pairs from the previous row:
new[k] = old[k-1] + old[k] - The
zip([0]+r, r+[0])pattern is the most concise iterative approach in Python - Use
math.comb(n, k)for direct computation of individual values - Pascal's Triangle appears in binomial expansion, grid path counting, and probability
- For code-golf, the padding-with-zeros approach produces the shortest Python solution

