Unit 9 Session 1 (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?
cake
tree is None
?
0
since there are no tiers in the cake.1
since the maximum number of tiers is 1.HAPPY CASE
Input: cake_sections = ["Chocolate", "Vanilla", "Strawberry", None, None, "Chocolate", "Coffee"]
Output: 3
Explanation: The longest path is from "Chocolate" -> "Strawberry" -> "Coffee".
Input: cake_sections = ["Vanilla"]
Output: 1
Explanation: The tree has only one node, so the maximum number of tiers is 1.
EDGE CASE
Input: cake_sections = []
Output: 0
Explanation: The tree is empty, so return 0.
Input: cake_sections = ["Chocolate", "Vanilla", "Strawberry", None, "Raspberry"]
Output: 3
Explanation: The longest path is from "Chocolate" -> "Vanilla" -> "Raspberry".
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 problems involving finding the maximum depth of a binary tree, we can consider the following approaches:
Plan the solution with appropriate visualizations and pseudocode.
Note: Like many interview questions, this problem can be solved multiple ways. If you used an iterative, BFS approach, take a look at the Maximum Tiers in Cake II solution.
1) Base Case:
cake
tree is empty (None
), return 0
.
2) Recursive Depth Calculation:Pseudocode:
1) Define the base case:
* If `cake` is `None`, return `0`.
2) Recursively calculate the depth of the left subtree (`left_depth = max_tiers(cake.left)`).
3) Recursively calculate the depth of the right subtree (`right_depth = max_tiers(cake.right)`).
4) Return `1 + max(left_depth, right_depth)` as the maximum number of tiers.
Implement the code to solve the algorithm.
class TreeNode:
def __init__(self, value, left=None, right=None):
self.val = value
self.left = left
self.right = right
def max_tiers(cake):
if not cake:
return 0
left_depth = max_tiers(cake.left)
right_depth = max_tiers(cake.right)
return 1 + max(left_depth, right_depth)
Review the code by running specific example(s) and recording values (watchlist) of your code's variables along the way.
cake_sections = ["Chocolate", "Vanilla", "Strawberry", None, None, "Chocolate", "Coffee"]
:
Evaluate the performance of your algorithm and state any strong/weak or future potential work.
Assume N
represents the number of nodes in the tree.
O(N)
because each node in the tree must be visited once.O(N)
due to the recursive call stack in the worst case, assuming a balanced tree.