Tutorialspoint
Problem
Solution
Submissions

Generate the Pascal’s Triangle

Certification: Basic Level Accuracy: 100% Submissions: 2 Points: 5

Write a C# program to generate Pascal's triangle up to 'n' rows. In Pascal's triangle, each number is the sum of the two numbers directly above it. The first row is always [1], and the first and last elements of each subsequent row are always 1.

Example 1
  • Input: numRows = 5
  • Output: [[1], [1,1], [1,2,1], [1,3,3,1], [1,4,6,4,1]]
  • Explanation:
    • Step 1: Create a list of lists to store the triangle rows.
    • Step 2: Add the first row [1] to the result.
    • Step 3: For row 2: Start with 1, end with 1. Result: [1,1]
    • Step 4: For row 3: Start with 1, calculate middle value 1+1=2, end with 1. Result: [1,2,1]
    • Step 5: For row 4: Start with 1, calculate middle values 1+2=3 and 2+1=3, end with 1. Result: [1,3,3,1]
    • Step 6: For row 5: Start with 1, calculate middle values 1+3=4, 3+3=6, and 3+1=4, end with 1. Result: [1,4,6,4,1]
Example 2
  • Input: numRows = 3
  • Output: [[1], [1,1], [1,2,1]]
  • Explanation:
    • Step 1: Create a list of lists to store the triangle rows.
    • Step 2: Add the first row [1] to the result.
    • Step 3: For row 2: Start with 1, end with 1. Result: [1,1]
    • Step 4: For row 3: Start with 1, calculate middle value 1+1=2, end with 1. Result: [1,2,1]
Constraints
  • 1 ≤ numRows ≤ 30
  • Time Complexity: O(n²)
  • Space Complexity: O(n²)
NumberControl StructuresWalmartSamsung
Editorial

Login to view the detailed solution and explanation for this problem.

My Submissions
All Solutions
Lang Status Date Code
You do not have any submissions for this problem.
User Lang Status Date Code
No submissions found.

Please Login to continue
Solve Problems

 
 
 
Output Window

Don't have an account? Register

Solution Hints

  • Use a list of lists to store each row of the triangle
  • Always start each row with 1
  • Calculate the middle elements of each row using the values from the previous row
  • Always end each row with 1
  • Build each row based on the previous row

Steps to solve by this approach:

 Step 1: Create a result list to store all rows of Pascal's triangle.
 Step 2: Add the first row [1] to the result.
 Step 3: For each subsequent row, start with 1.
 Step 4: Calculate middle elements by adding the two elements above from the previous row.
 Step 5: End each row with 1 and add the completed row to the result.

Submitted Code :