Unit 12 Session 1 Advanced (Click for link to problem statements)
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?
What is the goal of the problem?
wisdomLevel
-th row of the Wisdom Pyramid where each row is built by combining the two numbers directly above it from the previous row.What are the base cases?
[1]
.HAPPY CASE
Input:
wisdomLevel = 3
Output:
[1, 3, 3, 1]
Explanation:
The 3rd row of the Wisdom Pyramid is built by combining elements of the 2nd row:
[1, 2, 1] → [1, (1+2), (2+1), 1] = [1, 3, 3, 1].
EDGE CASE
Input:
wisdomLevel = 0
Output:
[1]
Explanation:
The 0th row is simply [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.
For pyramid row problems, we want to consider the following approaches:
Plan the solution with appropriate visualizations and pseudocode.
General Idea: We will use a dynamic programming approach to generate each row of the Wisdom Pyramid up to the specified wisdomLevel
. Each row is built by starting with 1
, calculating the middle elements based on the two numbers above, and ending with 1
.
Base Case:
wisdomLevel
is 0
, return [1]
.DP Array Initialization:
[1]
.Build the Rows:
1
to wisdomLevel
, generate the next row by:
1
.j
, calculate it as the sum of the two numbers directly above it from the previous row.1
.Return the Result:
wisdomLevel
.Implement the code to solve the algorithm.
def wisdom_pyramid(wisdomLevel):
if wisdomLevel == 0:
return [1]
dp = [[1]] # Initialize the first row of the pyramid
for i in range(1, wisdomLevel + 1):
# Start the row with 1
row = [1]
# Fill in the middle values
for j in range(1, i):
row.append(dp[i-1][j-1] + dp[i-1][j])
# End the row with 1
row.append(1)
dp.append(row)
return dp[wisdomLevel]
Review the code by running specific example(s) and recording values (watchlist) of your code's variables along the way.
Example 1:
wisdomLevel = 3
[1, 3, 3, 1]
Example 2:
wisdomLevel = 0
[1]
Example 3:
wisdomLevel = 5
[1, 5, 10, 10, 5, 1]
Evaluate the performance of your algorithm and state any strong/weak or future potential work.
Assume n
is the wisdomLevel
.
O(n^2)
because we need to generate all rows up to wisdomLevel
and each row takes linear time.O(n^2)
for storing the DP table containing all the rows of the pyramid.