Pascal's Triangle II — LeetCode #119 (Easy)
Tags: Array, Dynamic Programming
Related patterns: Dynamic Programming, Array
Brute Force approach
Time complexity: O(n²). Space complexity: O(1).
We can generate Pascal's Triangle row by row until we reach the desired rowIndex. Each row is built using the values from the previous row, making it straightforward but not the most efficient.
The time complexity is O(n²) because we build each row using the previous row, which takes linear time for each row, and we do this for n rows. The space complexity is O(1) since we only store the current row.
- Step 1: Initialize a list to hold the first row of Pascal's Triangle, which is [1].
- Step 2: For each row from 1 to rowIndex, create a new list starting with 1.
- Step 3: For each element in the new row (except the first and last), calculate its value by summing the two elements directly above it from the previous row.
- Step 4: Append 1 to the end of the new row and replace the previous row with the new row.
- Step 5: Repeat until the desired rowIndex is reached.
For rowIndex = 3:
1. Start with row = [1]
2. i = 1: new_row = [1, 1] → row = [1, 1]
3. i = 2: new_row = [1]; j = 1: new_row = [1, 2]; new_row = [1, 2, 1] → row = [1, 2, 1]
4. i = 3: new_row = [1]; j = 1: new_row = [1, 3]; j = 2: new_row = [1, 3, 3]; new_row = [1, 3, 3, 1] → row = [1, 3, 3, 1]
Optimal Solution approach
Time complexity: O(n). Space complexity: O(n).
We can compute the row directly using the properties of binomial coefficients, which allows us to build the row in a single pass without needing to store all previous rows.
The time complexity is O(n) because we compute each element of the row in constant time. The space complexity is O(n) as we store the entire row.
- Step 1: Initialize a list with size rowIndex + 1, filled with 0.
- Step 2: Set the first element to 1, as the first element of any row in Pascal's Triangle is always 1.
- Step 3: For each index from 1 to rowIndex, calculate the value using the formula: row[j] = row[j - 1] * (rowIndex - j + 1) / j.
- Step 4: Return the constructed row.
For rowIndex = 3:
1. Start with row = [1, 0, 0, 0]
2. j = 1: row[1] = 1 * (3 - 1 + 1) / 1 = 3 → row = [1, 3, 0, 0]
3. j = 2: row[2] = 3 * (3 - 2 + 1) / 2 = 3 → row = [1, 3, 3, 0]
4. j = 3: row[3] = 3 * (3 - 3 + 1) / 3 = 1 → row = [1, 3, 3, 1]
Key Insights
- Each element in a row is the sum of the two elements directly above it.
- The nth row can be computed directly using binomial coefficients.
Common Mistakes
- Not understanding how to build the triangle row by row.
- Confusing the indices when accessing elements from the previous row.
Interview Tips
- Always clarify the problem requirements before jumping into coding.
- Think about edge cases, like rowIndex = 0 or rowIndex = 1.
- Explain your thought process clearly while coding.