KatInterview

118. Pascal's Triangle

EasySolutions in Python, Java, C++, TypeScript

Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.

Approach

The problem asks us to generate the first numRows of Pascal's triangle. Pascal's triangle is a triangular array of binomial coefficients. The key properties are:

Solution

Pascal's Triangle in Python

class Solution:
    def generate(self, numRows: int) -> List[List[int]]:
        # The problem constraint is 1 <= numRows.
        # Initialize the triangle with the first row, which is always [1].
        triangle = [[1]]

        # Iterate from the second row (index 1) up to numRows.
        for i in range(1, numRows):
            # Get the previous row from the triangle.
            prev_row = triangle[-1]
            # Start the current row with 1.
            current_row = [1]
            
            # Calculate the middle elements by summing adjacent elements of the previous row.
            # The loop runs for len(prev_row) - 1 times, which is i-1 times.
            for j in range(len(prev_row) - 1):
                current_row.append(prev_row[j] + prev_row[j+1])
            
            # End the current row with 1.
            current_row.append(1)
            
            # Add the complete current row to the triangle.
            triangle.append(current_row)
            
        return triangle

Pascal's Triangle in Java

class Solution {
    public List<List<Integer>> generate(int numRows) {
        // Initialize the list of lists to store the triangle.
        List<List<Integer>> triangle = new ArrayList<>();
        
        // The problem constraint is 1 <= numRows, so we can directly add the first row.
        // The first row is always [1].
        List<Integer> firstRow = new ArrayList<>();
        firstRow.add(1);
        triangle.add(firstRow);

        // Iterate from the second row (i=1) up to numRows-1.
        for (int i = 1; i < numRows; i++) {
            // Get the previous row to calculate the current row.
            List<Integer> prevRow = triangle.get(i - 1);
            List<Integer> currentRow = new ArrayList<>();
            
            // The first element of any row is always 1.
            currentRow.add(1);
            
            // Calculate the middle elements.
            // Each element is the sum of the two elements directly above it.
            for (int j = 1; j < i; j++) {
                currentRow.add(prevRow.get(j - 1) + prevRow.get(j));
            }
            
            // The last element of any row is always 1.
            currentRow.add(1);
            
            // Add the newly generated row to the triangle.
            triangle.add(currentRow);
        }
        
        return triangle;
    }
}

Pascal's Triangle in C++

class Solution {
public:
    vector<vector<int>> generate(int numRows) {
        // Initialize the result vector which will store the triangle.
        vector<vector<int>> triangle;
        
        // The problem constraint is 1 <= numRows, so we don't need to handle numRows = 0.
        // The first row is always [1].
        triangle.push_back({1});

        // Iterate from the second row (i=1) up to numRows-1.
        for (int i = 1; i < numRows; ++i) {
            // Get a reference to the previous row to calculate the current row.
            vector<int>& prev_row = triangle.back();
            
            // Start the current row with 1.
            vector<int> current_row = {1};
            
            // Calculate the middle elements of the current row.
            // Each element is the sum of the two elements directly above it.
            // The j-th element of the current row (i) is calculated from the (j-1)-th and j-th elements of the previous row (i-1).
            for (int j = 1; j < i; ++j) {
                current_row.push_back(prev_row[j - 1] + prev_row[j]);
            }
            
            // The last element of each row is also 1.
            current_row.push_back(1);
            
            // Add the newly generated row to the triangle.
            triangle.push_back(current_row);
        }
        
        return triangle;
    }
};

Pascal's Triangle in TypeScript

function generate(numRows: number): number[][] {
    // The problem constraint is 1 <= numRows.
    // Initialize the triangle with the first row, which is always [1].
    const triangle: number[][] = [[1]];

    // Iterate from the second row (index 1) up to numRows.
    for (let i = 1; i < numRows; i++) {
        // Get the previous row to calculate the current one.
        const prevRow = triangle[i - 1];
        // Start the current row with 1.
        const currentRow: number[] = [1];
        
        // Calculate the middle elements.
        // Each element is the sum of the two elements directly above it.
        for (let j = 1; j < i; j++) {
            currentRow.push(prevRow[j - 1] + prevRow[j]);
        }
        
        // End the current row with 1.
        currentRow.push(1);
        
        // Add the completed row to the triangle.
        triangle.push(currentRow);
    }
    
    return triangle;
};

Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.

LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.