#118
Pascal's Triangle
EasyArrayDynamic ProgrammingDynamic ProgrammingArray
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n²) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n²)Space O(n)
The optimal solution builds each row based on the previous row, reusing the list to minimize space usage. This approach is efficient in both time and space, as it only requires storing the current and previous rows.
⚙️
Algorithm
5 steps- 1Step 1: Initialize a list to hold the first row as [1].
- 2Step 2: For each subsequent row, create a new list starting with 1.
- 3Step 3: Calculate each element in the row using the last row, and append it to the new row.
- 4Step 4: Append 1 at the end of the new row.
- 5Step 5: Replace the previous row with the new row and repeat until all rows are generated.
solution.py13 lines
1# Full working Python code
2
3def generate(numRows):
4 triangle = []
5 for row_num in range(numRows):
6 row = [1] # Start with 1
7 if triangle:
8 last_row = triangle[-1]
9 for j in range(1, len(last_row)):
10 row.append(last_row[j - 1] + last_row[j])
11 row.append(1) # End with 1
12 triangle.append(row)
13 return triangleℹ
Complexity note: The time complexity remains O(n²) since we still generate n rows with each row containing up to n elements. The space complexity is O(n) due to storing the triangle in a list.
- 1Each element in Pascal's triangle is the sum of the two elements directly above it.
- 2The triangle is symmetric, meaning row n is the same as row n reversed.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.