Tutorialspoint
Problem
Solution
Submissions

Generate Pascal's Triangle Up to N Rows

Certification: Basic Level Accuracy: 56.25% Submissions: 64 Points: 10

Write a Python program that generates Pascal's Triangle up to N rows.

Example 1
  • Input: N = 5
  • Output:
     [1]
     [1, 1]
     [1, 2, 1]
     [1, 3, 3, 1]
     [1, 4, 6, 4, 1]
  • Explanation:
    • Step 1: Start with the first row as [1].
    • Step 2: To generate the next row, add adjacent elements of the previous row.
    • Step 3: Each row starts and ends with 1.
    • Step 4: Continue this process until we have N rows.
Example 2
  • Input: N = 3
  • Output:
    [1]
    [1, 1]
    [1, 2, 1]
  • Explanation:
    • Step 1: Start with the first row as [1].
    • Step 2: Generate the second row as [1, 1].
    • Step 3: Generate the third row by adding adjacent elements of the second row: [1, 1+1, 1] = [1, 2, 1].
Constraints
  • 0 ≤ N ≤ 30
  • Time Complexity: O(n²)
  • Space Complexity: O(n²)
ArraysControl StructuresGoogleGoldman Sachs
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

  • Start with the first row as [1]
  • Each row can be built using: row[i] = prev_row[i-1] + prev_row[i] for middle elements

The following are the steps to solve:

  • Initialize an empty list to store the triangle
  • For each row, create a new list with the correct number of elements
  • The first and last elements of each row are always 1
  • Calculate middle elements using the formula: row[j] = previous_row[j-1] + previous_row[j]
  • Add each row to the triangle
  • Return the completed triangle

Submitted Code :