KatInterview

Centered Pascal Pyramid Renderer

StringsAuto-graded · 15 test cases
MediumAuto-gradedStringspascal-trianglestring-formattingsimulation

Last updated

Build the first n rows of Pascal's triangle and render them as a centered text pyramid with fixed-width, right-aligned cells and floor-based indentation.

Write a function that builds the first n_rows rows of Pascal's triangle and returns them as a single multi-line string, laid out as a centered pyramid.

Row r (starting at 0) contains the binomial coefficients C(r, 0), C(r, 1), ..., C(r, r).

Layout rules

  1. Let max_value be the largest number anywhere in the triangle, and let w be the number of decimal digits in max_value.
  2. Write every number right-aligned in a cell of exactly w characters, padding on the left with spaces.
  3. Within a row, join the cells with exactly one space between neighbors. Call the result the row's body.
  4. Let L be the length of the body of the last row (the widest one).
  5. For each row, put (L - len(body)) // 2 spaces (integer floor division) in front of its body. This is the only padding added.
  6. Do not add trailing spaces to any line.
  7. Join the lines with a single newline character "\n", with no newline after the last line.

Because the indent uses floor division, the pyramid may lean by half a column when w is even. Follow the rule exactly as stated.

Task

Return the resulting string for a given n_rows.

Constraints

  • 1 <= n_rows <= 60
  • The function returns a str; it does not print anything.
  • Every row has no trailing whitespace, and the whole string has no trailing newline.

Examples

Example 1

Input: render_pascal_pyramid(5)

Output: ' 1\n 1 1\n 1 2 1\n 1 3 3 1\n1 4 6 4 1'

Example 2

Input: render_pascal_pyramid(1)

Output: '1'

Example 3

Input: render_pascal_pyramid(3)

Output: ' 1\n 1 1\n1 2 1'

Hints

Hint 1

Row r of Pascal's triangle is just C(r, 0..r), or you can build it from the previous row by adding adjacent pairs.

Hint 2

The widest number always appears in the last row, but computing the maximum over all rows is just as safe. Its digit count gives the cell width.

Hint 3

Build each row's body first (right-aligned cells joined by one space), then use the length of the last body to compute each row's indent with floor division.