Print a Centered Pascal Triangle
Company: Faire
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: medium
Interview Round: Technical Screen
Given a positive integer `height`, generate the first `height` rows of Pascal's triangle and print them as a centered text triangle.
Formatting requirements:
- Let `max_value` be the largest number that appears in the triangle.
- Let `w` be the number of decimal digits in `max_value`.
- Print each number right-aligned in a field of width `w`.
- Use consistent spacing between values so the output looks visually symmetric.
- Add leading spaces so each row is centered relative to the last row.
Example: if the largest value is `121`, then `w = 3`, so the value `1` should be printed as `" 1"`.
Quick Answer: This question evaluates the ability to generate combinatorial structures (Pascal's triangle) and apply precise numeric formatting, alignment, and string-layout skills, reflecting algorithmic thinking and attention to presentation details.
Given a positive integer `height`, generate the first `height` rows of Pascal's triangle and return them as a list of strings representing a centered text triangle. If the returned strings are printed line by line, they should form a visually symmetric Pascal triangle.
Formatting rules:
- Let `max_value` be the largest number anywhere in the generated triangle.
- Let `w` be the number of decimal digits in `max_value`.
- Format every number right-aligned in a field of width `w`.
- Separate adjacent formatted numbers with exactly one space.
- Let `last_width` be the length of the formatted last row.
- For each row, add `floor((last_width - current_row_width) / 2)` leading spaces so it is centered relative to the last row.
- Do not include trailing spaces in the returned strings.
Example: if `max_value = 121`, then `w = 3`, so the value `1` should be formatted as `' 1'`.
Constraints
- 1 <= height <= 30
- Each interior value in Pascal's triangle is the sum of the two values directly above it
Examples
Input: (1,)
Expected Output: ['1']
Explanation: The triangle has only one row, so the result is just ['1'].
Input: (2,)
Expected Output: [' 1', '1 1']
Explanation: With height 2, the last row is '1 1' and the first row is centered above it with one leading space.
Hints
- Build Pascal's triangle row by row: every row starts and ends with 1, and each middle value comes from two adjacent values in the previous row.
- Because the spacing depends on the largest value and the width of the last row, generate all rows first and format them in a second pass.