Tutorialspoint
Problem
Solution
Submissions

Pascal's Triangle

Certification: Basic Level Accuracy: 0% Submissions: 0 Points: 5

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 1
  • Input: numRows = 5
  • Output: [[1],[1,1],[1,2,1],[1,3,3,1],[1,4,6,4,1]]
  • Explanation:
     Step 1: Row 0: [1]
     Step 2: Row 1: [1,1]
     Step 3: Row 2: [1,2,1] (2 = 1+1)
     Step 4: Row 3: [1,3,3,1] (3 = 1+2, 3 = 2+1)
     Step 5: Row 4: [1,4,6,4,1] (4 = 1+3, 6 = 3+3, 4 = 3+1)
Example 2
  • Input: numRows = 1
  • Output: [[1]]
  • Explanation:
     Step 1: Only 1 row is requested
     Step 2: Row 0: [1]
Constraints
  • 1 <= numRows <= 30
  • Each row contains exactly i+1 elements where i is the row index (0-indexed)
  • The values in Pascal's triangle won't exceed 2^31 - 1
  • Time Complexity: O(numRows^2)
  • Space Complexity: O(numRows^2) to store the triangle
ArraysPwCShopify
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

  • Initialize the triangle with the first row as [1]
  • For each subsequent row, start and end with 1
  • For the middle elements, compute each value as the sum of the two numbers above it
  • Use the previous row to calculate values for the current row
  • Continue this process until all numRows are generated

Steps to solve by this approach:

 Step 1: Allocate memory for storing the triangle - an array of pointers for each row.

 Step 2: Allocate memory for tracking the size of each row - each row i has i+1 elements.
 Step 3: For each row, start by setting the first and last elements to 1, as these are always 1 in Pascal's triangle.
 Step 4: For middle elements (j from 1 to i-1), calculate the value by adding the two elements above it: triangle[i-1][j-1] + triangle[i-1][j].
 Step 5: Continue this process for all rows from 0 to numRows-1.
 Step 6: Set the returnSize to numRows to indicate the number of rows generated.
 Step 7: Return the resulting triangle array.

Submitted Code :