Pascals Triangle

Solution For Pascals Triangle

Problem Statement:

Given a non-negative integer numRows, generate the first numRows of Pascal’s triangle.

Example:

Input: 5

Output: [[1],[1,1],[1,2,1],[1,3,3,1],[1,4,6,4,1]]

Solution:

The problem requires us to generate the first numRows of Pascal’s triangle. For this, we can iterate through each row from 0 to numRows and generate each row of the Pascal’s triangle.

The first and the last element of each row is always 1. For all other elements, we can calculate them based on the elements in the previous row. Specifically, the value of element i in row j is equal to the sum of element i-1 and i in row j-1.

The solution approach can be summarized in the following steps:

  1. Create an empty 2D list.
  2. Iterate through each row from 0 to numRows.
  3. If the current row is the first row, then add [1] to the 2D list.
  4. If the current row is not the first row:
    a. Create an empty list.
    b. Append 1 to the list.
    c. Iterate through each element in the previous row (except the first and last elements):
    i. Calculate the value of the current element using the formula mentioned above.
    ii. Append the value to the list.
    d. Append 1 to the list.
    e. Add the list to the 2D list.
  5. Return the 2D list.

Time Complexity:

The time complexity is O(numRows^2) because we are iterating through numRows for generating each row of the Pascal’s triangle.

Space Complexity:

The space complexity is also O(numRows^2) because we are storing all the elements of the Pascal’s triangle in a 2D list.

Python Code:

def generate(numRows: int) -> List[List[int]]:
triangle = [] for i in range(numRows):
row = [] if i == 0:
row = [1] else:
prev_row = triangle[i-1] row.append(1)
for j in range(1, i):
row.append(prev_row[j-1] + prev_row[j])
row.append(1)
triangle.append(row)
return triangle

Note:

Here, we are using type hints for function parameters and return values. Also, we are importing the List type from the typing module which is used for type hints.

Step by Step Implementation For Pascals Triangle

/*
Given a non-negative integer numRows, generate the first numRows of Pascal's triangle.

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

Example:

Input: 5
Output:
[
     [1],
    [1,1],
   [1,2,1],
  [1,3,3,1],
 [1,4,6,4,1]
]
*/

class Solution {
    public List> generate(int numRows) {
        List> triangle = new ArrayList>(); 
  
        // First row is always [1]
        triangle.add(new ArrayList<>());
        triangle.get(0).add(1);
    
        for (int rowNum = 1; rowNum < numRows; rowNum++) {
            List row = new ArrayList<>(); 
            List prevRow = triangle.get(rowNum-1); 
  
            // The first row element is always 1
            row.add(1); 
  
            // Each triangle element (other than the first and last of each row)
            // is equal to the sum of the elements above-and-to-the-left and
            // above-and-to-the-right.
            for (int j = 1; j < rowNum; j++) {
                row.add(prevRow.get(j-1) + prevRow.get(j));
            }
  
            // The last row element is always 1
            row.add(1); 
  
            triangle.add(row); 
        }
  
        return triangle;
    }
}
# Given a non-negative integer numRows, generate the first numRows of Pascal's triangle.

# In Pascal's triangle, each number is the sum of the two numbers directly above it.

# Example:

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

def generate(numRows):
    """
    :type numRows: int
    :rtype: List[List[int]]
    """
    
    # Base case: If numRows is 0 or 1, return empty or single-element list
    if numRows == 0:
        return []
    elif numRows == 1:
        return [[1]]
    
    # Otherwise, initialize triangle with two rows
    triangle = [[1], [1, 1]]
    
    # Iteratively generate remaining rows
    for i in range(2, numRows):
        # Start with the list corresponding to the row above
        row = triangle[i-1]
        # Initialize current row with 1 in the first position
        current_row = [1]
        # Generate elements of current row by summing adjacent elements of the row above
        for j in range(len(row)-1):
            current_row.append(row[j] + row[j+1])
        # Append 1 to the end of the current row
        current_row.append(1)
        # Append current row to triangle
        triangle.append(current_row)
    
    return triangle
var generate = function(numRows) {
    // Create an empty array of arrays to hold the pascal triangle
    let pascalTriangle = [];
    
    // For loop to iterate through each row of the triangle
    for(let i = 0; i < numRows; i++) {
        // Create an empty array to store the values in the current row
        let row = [];
        
        // For loop to iterate through each column of the current row
        for(let j = 0; j <= i; j++) {
            // If we are on the first or last column of the row, the value will be 1
            if(j === 0 || j === i) {
                row.push(1);
            } else {
                // Otherwise, the value will be the sum of the values in the previous row at the current column and the column before it
                row.push(pascalTriangle[i-1][j] + pascalTriangle[i-1][j-1]);
            }
        }
        // Push the row array into the pascalTriangle array
        pascalTriangle.push(row);
    }
    // Return the pascalTriangle array
    return pascalTriangle;
};
vector> generate(int numRows) {
    vector> result;
    if (numRows == 0) {
        return result;
    }
    result.push_back(vector(1, 1));
    for (int i = 1; i < numRows; i++) {
        vector row(1, 1);
        for (int j = 1; j < i; j++) {
            row.push_back(result[i-1][j-1] + result[i-1][j]);
        }
        row.push_back(1);
        result.push_back(row);
    }
    return result;
}
public IList> Generate(int numRows) {
    
    //Create an empty list of lists
    IList> triangle = new List>();

    //For each row in the triangle
    for (int i = 0; i < numRows; i++)
    {
        //Create a new list
        IList row = new List();

        //For each element in the row
        for (int j = 0; j <= i; j++)
        {
            //If the element is the first or last in the row
            if (j == 0 || j == i)
            {
                //Set the value to 1
                row.Add(1);
            }
            else
            {
                //Set the value to the sum of the elements in the previous row
                row.Add(triangle[i-1][j-1] + triangle[i-1][j]);
            }
        }

        //Add the row to the triangle
        triangle.Add(row);
    }

    //Return the triangle
    return triangle;
}


Scroll to Top
[gravityforms id="5" description="false" titla="false" ajax="true"]