Taro Logo

Pascal's Triangle

#101 Most AskedEasy
Topics:
Arrays

Given an integer numRows, return the first numRows of Pascal's triangle.

In Pascal's triangle, each number is the sum of the two numbers directly above it as shown:

Example 1:

Input: numRows = 5
Output: [[1],[1,1],[1,2,1],[1,3,3,1],[1,4,6,4,1]]

Example 2:

Input: numRows = 1
Output: [[1]]

Constraints:

  • 1 <= numRows <= 30

Solution


Clarifying Questions

When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:

  1. What is the maximum value of `numRows` we should expect, and should we handle constraints like `numRows = 0`?
  2. Should the output for `numRows = 0` be an empty list `[]`, or should it return an empty list inside a list `[[]]`?
  3. Are there any specific memory or space complexity constraints we need to optimize for beyond the standard output storage?
  4. Can we assume that `numRows` will always be a valid non-negative integer, or do we need to handle invalid or null inputs?
  5. Is there a preferred way to handle potential integer overflow if `numRows` is large, or do standard 32-bit/64-bit integers suffice?

Brute Force Solution

Approach

Imagine you are building a pyramid of numbers from the ground up, where each new row is created by looking at the numbers in the row directly above it. The brute force strategy involves manually figuring out every single number in the first row, then calculating every number in the second row, and continuing this process step-by-step until you reach the desired height of the pyramid.

Here's how the algorithm would work step-by-step:

  1. Start by deciding how tall you want your pyramid of numbers to be.
  2. Begin with the very top row, which always consists of a single number placed in the center.
  3. For the next row down, figure out each new position by looking at the two numbers touching it from the row above and adding them together.
  4. Repeat this addition process for every single position across the current row until it is completely filled.
  5. Move down to the next row and repeat the exact same process of adding adjacent pairs from the row above to fill in the new values.
  6. Continue this pattern row by row, building downwards until you have created the exact number of rows requested.
  7. Gather all the completed rows together to reveal the final finished pyramid of numbers.

Code Implementation

def generate(num_rows):
    triangle_rows = []

    # We build the triangle row by row from top to bottom since each row depends on the previous one
    for current_row_index in range(num_rows):
        current_row = [None] * (current_row_index + 1)
        current_row[0] = 1
        current_row[current_row_index] = 1

        # We fill in the middle values by summing the two adjacent numbers from the row directly above
        for element_index in range(1, current_row_index):
            previous_row = triangle_rows[current_row_index - 1]
            current_row[element_index] = previous_row[element_index - 1] + previous_row[element_index]

        triangle_rows.append(current_row)

    # We collect all generated rows together to form the final complete pyramid structure
    return triangle_rows

Big(O) Analysis

Time Complexity
O(n²) – The input size n represents the total number of rows requested for the triangle. Building the pyramid requires a nested approach where the outer loop iterates n times to generate each row, and the inner loop calculates the elements within that row. As we move down the triangle, row i requires i additions to determine the intermediate values. Summing the number of operations across all n rows results in approximately n * (n + 1) / 2 total additions, which simplifies to a quadratic time complexity of O(n²).
Space Complexity
O(N^2) – To build the pyramid of numbers, we allocate a two-dimensional list structure to store all the generated rows and their elements. Specifically, row i requires space for i + 1 integers, meaning the total number of elements stored across all rows is the sum from 1 to N. As the requested height N of the pyramid grows, the cumulative size of these stored rows scales quadratically with N. Therefore, the overall auxiliary space complexity simplifies to O(N^2).

Optimal Solution

Approach

To build the triangle efficiently, we construct it level by level from the top down. Each new level is created by looking at the level directly above it and using a simple addition pattern to determine the numbers.

Here's how the algorithm would work step-by-step:

  1. Begin at the very top with the first level, which always contains just a single starting number.
  2. For every subsequent level, realize that it will always start and end with the same starting number.
  3. To find the values that sit between the outer edges, look at the level directly above you and add together each adjacent pair of numbers side by side.
  4. Place these newly added sums neatly between the outer edges to form the interior numbers of the current level.
  5. Continue this process of building each new level based on the completed level just before it until you reach the desired total number of levels.

Code Implementation

def generate(num_rows):
    triangle_container = []

    # We build the triangle level by level from the top down to construct the full structure.
    for current_row_index in range(num_rows):
        current_row_values = [1] * (current_row_index + 1)

        # Interior elements are computed using the sum of adjacent pairs from the previous level.
        for element_index in range(1, current_row_index):
            left_above = triangle_container[current_row_index - 1][element_index - 1]
            right_above = triangle_container[current_row_index - 1][element_index]
            current_row_values[element_index] = left_above + right_above

        triangle_container.append(current_row_values)

    return triangle_container

Big(O) Analysis

Time Complexity
O(n²) – The input size n represents the total number of levels we need to build in Pascal's Triangle. To construct these levels, we use nested iteration where the outer loop runs n times for each level and the inner loop computes the values by adding adjacent pairs, performing i additions for the i-th level. Summing the work done across all n levels results in approximately n * (n + 1) / 2 total operations. As n grows large, this quadratic workload simplifies to a Big O time complexity of O(n²).
Space Complexity
O(numRows^2) – To construct Pascal's Triangle level by level, we allocate a dynamic list of lists to store the results, where the i-th row contains i elements. The total number of integers stored across all rows forms a triangular sum equivalent to (numRows * (numRows + 1)) / 2 elements. Therefore, the auxiliary space scales quadratically with respect to the input size N, representing the total number of rows. No additional deep recursion or heavy auxiliary data structures are utilized beyond the output storage itself.

Edge Cases

numRows is 0
How to Handle:
Return an empty list immediately as no rows need to be generated.
numRows is 1
How to Handle:
Return a list containing a single inner list with the element 1.
numRows is 2
How to Handle:
Return two rows where the first is [1] and the second is [1, 1].
Maximum expected input like numRows equals 30
How to Handle:
The O(n squared) time and space complexity easily fits within standard memory and time limits.
Integer overflow for large numRows values
How to Handle:
Standard 32-bit integers suffice up to numRows equals 30 before values exceed integer limits.
Symmetric row generation behavior
How to Handle:
The inner loop correctly builds each row using the boundary values 1 and the sum of the two elements directly above.
0/245 completed