Tutorialspoint
Problem
Solution
Submissions

Pascal's Triangle

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

Write a Java program to generate the first numRows of Pascal's triangle. In Pascal's triangle, each number is the sum of the two numbers directly above it. For example, the first few rows of Pascal's triangle are:

    1

1 1
1 2 1
1 3 3 1
1 4 6 4 1
Example 1
  • Input: numRows = 5
  • Output: [[1],[1,1],[1,2,1],[1,3,3,1],[1,4,6,4,1]]
  • Explanation:
    • Row 1: [1]
    • Row 2: [1,1]
    • Row 3: [1,2,1]
    • Row 4: [1,3,3,1]
    • Row 5: [1,4,6,4,1]
    • Therefore, the output is [[1],[1,1],[1,2,1],[1,3,3,1],[1,4,6,4,1]].
Example 2
  • Input: numRows = 1
  • Output: [[1]]
  • Explanation:
    • Row 1: [1]
    • Therefore, the output is [[1]].
Constraints
  • 1 ≤ numRows ≤ 30
  • Time Complexity: O(numRows^2)
  • Space Complexity: O(numRows^2)
NumberListTech MahindraSamsung
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

  • Create a list of lists to store the triangle
  • The first row always contains a single element, 1
  • For each subsequent row, calculate each element as the sum of the two elements above it
  • The first and last elements of each row are always 1
  • Add each generated row to the result list

Steps to solve by this approach:

 Step 1: Create a list of lists to store the triangle.

 Step 2: Add the first row [1] to the result.
 Step 3: For each subsequent row from 1 to numRows-1:
 Step 4: Create a new list for the current row and add 1 as the first element.
 Step 5: For the middle elements, add the sum of the elements directly above from the previous row.
 Step 6: Add 1 as the last element of the current row.
 Step 7: Add the current row to the result and return the complete triangle.

Submitted Code :