Understand what the interviewer is asking for by using test cases and questions about the problem.
- Established a set (2-3) of test cases to verify their own solution later.
- Established a set (1-2) of edge cases to verify their solution handles complexities.
- Have fully understood the problem and have no clarifying questions.
- Have you verified any Time/Space Constraints for this problem?
Be sure that you clarify the input and output parameters of the problem:
O(n^2)
time and O(n)
space will do. Run through a set of example cases:
Input: rowIndex = 3
Output: [1,3,3,1]
Input: rowIndex = 1
Output: [1,1]
EDGE CASE
Input: rowIndex = 0
Output: [1]
Match what this problem looks like to known categories of problems, e.g. Linked List or Dynamic Programming, and strategies or patterns in those categories.
Plan the solution with appropriate visualizations and pseudocode.
General Idea: Bottom-Up DP Technique, we will build up our answer. We will find the next row of the pascal triangle from the previous row. We can add zeros to the beginning and end of row to help with calculation of next row. We will reuse the previous row to save memory
1. Set the basecase, [1] in result
2. Generate number of rows as requested
a. Add zeros to the beginning and end of previous row for calculation
b. For each item in row, set it to be itself plus the next number.
c. Remove the last zero, because we only need one new number
d. Set the new row to result
3. Return the results
⚠️ Common Mistakes
Implement the code to solve the algorithm.
class Solution:
def getRow(self, rowIndex: int) -> List[int]:
# Set the basecase, [1] in results
result = [1]
# Generate number of rows as requested
for i in range(rowIndex):
# Add zeros to the beginning and end of previous row for calculation
row = [0] + result + [0]
# For each item in row, set it to be itself plus the next number
for j in range(len(row) - 1):
row[j] = row[j] + row[j + 1]
# Remove the last zero, because we only need one new number
row.pop()
# Set the new row to result
result = row
# Return the results
return result
class Solution {
public List<Integer> getRow(int k) {
Integer[] arr = new Integer[k + 1];
Arrays.fill(arr, 0);
// Set the basecase, [1] in results
arr[0] = 1;
// Generate number of rows as requested
for (int i = 1; i <= k; i++)
// For each item in row, set it to be itself plus the previous number
for (int j = i; j > 0; j--)
arr[j] = arr[j] + arr[j - 1];
return Arrays.asList(arr);
}
}
Review the code by running specific example(s) and recording values (watchlist) of your code's variables along the way.
Evaluate the performance of your algorithm and state any strong/weak or future potential work.
Assume N
represents the number of rows
O(N^2)
, because we need to build up each row, and the number of items in each rows averages N/2
items. O(N)
, because we need to hold the row with N
items in memory.