Codepath

Sorting Plants by Rarity

Unit 8 Session 2 Standard (Click for link to problem statements)

Unit 8 Session 2 Advanced (Click for link to problem statements)

Problem Highlights

  • 💡 Difficulty: Medium
  • Time to complete: 20-25 mins
  • 🛠️ Topics: Trees, Binary Search Trees, Inorder Traversal

1: U-nderstand

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 structure of the tree?
    • The tree is a Binary Search Tree (BST) where each node represents a plant, with a key indicating its rarity.
  • What operation needs to be performed?
    • An inorder traversal of the BST to produce a sorted list of plant nodes as (key, val) tuples.
  • What should be returned?
    • A list of tuples representing the plants, sorted from least to most rare.
HAPPY CASE
Input: [(3, "Monstera"), (1, "Pothos"), (2, "Spider Plant"), (5, "Witchcraft Orchid"), (4, "Hoya Motoskei")]
Output: [(1, "Pothos"), (2, "Spider Plant"), (3, "Monstera"), (4, "Hoya Motoskei"), (5, "Witchcraft Orchid")]
Explanation: The plants are sorted by rarity in ascending order.

EDGE CASE
Input: None
Output: []
Explanation: An empty tree should return an empty list.

2: M-atch

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 Binary Search Tree (BST) problems, we want to consider the following approaches:

  • Inorder Traversal: Inorder traversal of a BST returns the nodes in sorted order by key.
  • Recursion: A recursive approach can be used to perform the inorder traversal and collect the nodes in the desired order.

3: P-lan

Plan the solution with appropriate visualizations and pseudocode.

General Idea: Perform an inorder traversal of the BST and collect the nodes as (key, val) tuples in a list.

1) Initialize an empty list `result` to store the sorted plant nodes.
2) Define a helper function `inorder(node)` to perform the traversal:
    - If the current node is not `None`, recursively traverse the left subtree.
    - Append the current node's `(key, val)` tuple to the `result` list.
    - Recursively traverse the right subtree.
3) Call the `inorder` function on the root of the BST.
4) Return the `result` list containing the nodes in sorted order.

⚠️ Common Mistakes

  • Forgetting to handle the case where the tree is empty, which should return an empty list.
  • Not correctly performing the inorder traversal, which might result in an unsorted list.

4: I-mplement

Implement the code to solve the algorithm.

class TreeNode:
    def __init__(self, val, key=None, left=None, right=None):
        self.val = val    # Plant's name
        self.key = key if key is not None else val  # Default key to val if key is not provided
        self.left = left
        self.right = right

def sort_plants(collection):
    result = []
    
    def inorder(node):
        if node is not None:
            inorder(node.left)
            result.append((node.key, node.val))
            inorder(node.right)
    
    inorder(collection)
    return result

5: R-eview

Review the code by running specific example(s) and recording values (watchlist) of your code's variables along the way.

- Example 1:
    - Input: `collection = TreeNode(3, "Monstera", TreeNode(1, "Pothos", None, TreeNode(2, "Spider Plant")), TreeNode(5, "Witchcraft Orchid", TreeNode(4, "Hoya Motoskei")))`
    - Execution: 
        - Start at root (3, "Monstera").
        - Traverse left subtree:
            - Visit (1, "Pothos"), then right to (2, "Spider Plant").
        - Add (3, "Monstera").
        - Traverse right subtree:
            - Visit (5, "Witchcraft Orchid"), then left to (4, "Hoya Motoskei").
    - Output: `[(1, "Pothos"), (2, "Spider Plant"), (3, "Monstera"), (4, "Hoya Motoskei"), (5, "Witchcraft Orchid")]`
- Example 2:
    - Input: `collection = None`
    - Execution: Tree is empty, return an empty list.
    - Output: `[]`

6: E-valuate

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.

  • Time Complexity: O(N) because we must visit each node once during the inorder traversal.
  • Space Complexity: O(N) for the space used to store the result list and the recursion stack in the worst case (for a skewed tree).
Fork me on GitHub