Codepath

Minimum Difference in Pearl Size

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 pearl with a specific size.
  • What operation needs to be performed?
    • The function needs to find the minimum difference between the sizes of any two different pearls.
  • What should be returned?
    • The function should return the minimum difference between the sizes of any two different pearls.
HAPPY CASE
Input: pearls = Pearl(4, Pearl(2, Pearl(1), Pearl(3)), Pearl(6, None, Pearl(8)))
Output: 1
Explanation: The smallest difference is between the sizes 3 and 4 or between 2 and 3, both of which have a difference of 1.

EDGE CASE
Input: pearls = Pearl(4)
Output: Infinity or some large value depending on implementation
Explanation: With only one pearl, there is no difference to calculate.

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: An inorder traversal of a BST returns the nodes in sorted order by value. This allows for the direct comparison of consecutive nodes to find the minimum difference.

3: P-lan

Plan the solution with appropriate visualizations and pseudocode.

General Idea: Perform an inorder traversal of the BST to obtain the nodes in sorted order. As we traverse, keep track of the previous node and compute the difference with the current node, updating the minimum difference found.

1) Initialize `prev` to `None` and `min_diff` to infinity.
2) Define a helper function `inorder_traversal(node, prev, min_diff)` that:
    - If the node is `None`, return the current `prev` and `min_diff`.
    - Recursively traverse the left subtree.
    - Update `min_diff` with the difference between the current node value and `prev` if `prev` is not `None`.
    - Set `prev` to the current node value.
    - Recursively traverse the right subtree.
3) Call `inorder_traversal(pearls, prev, min_diff)` starting from the root of the tree.
4) Return `min_diff`.

⚠️ Common Mistakes

  • Not correctly handling edge cases where the tree has fewer than two nodes.
  • Forgetting to update the prev value as we traverse the tree.

4: I-mplement

Implement the code to solve the algorithm.

class Pearl:
    def __init__(self, size=0, left=None, right=None):
        self.val = size
        self.left = left
        self.right = right

def min_diff_in_pearl_sizes(pearls):
    def inorder_traversal(node, prev, min_diff):
        if not node:
            return prev, min_diff
        
        # Traverse the left subtree
        prev, min_diff = inorder_traversal(node.left, prev, min_diff)
        
        # Update the minimum difference
        if prev is not None:
            min_diff = min(min_diff, node.val - prev)
        
        # Update the previous node value
        prev = node.val
        
        # Traverse the right subtree
        return inorder_traversal(node.right, prev, min_diff)
    
    # Initialize prev as None and min_diff as infinity
    prev = None
    min_diff = float('inf')
    
    # Perform the inorder traversal and get the result
    _, min_diff = inorder_traversal(pearls, prev, min_diff)
    
    return min_diff

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: `pearls = Pearl(4, Pearl(2, Pearl(1), Pearl(3)), Pearl(6, None, Pearl(8)))`
    - Execution: 
        - Perform inorder traversal: 1 -> 2 -> 3 -> 4 -> 6 -> 8.
        - Differences: (2-1), (3-2), (4-3), (6-4), (8-6).
        - Minimum difference: 1.
    - Output: `1`
- Example 2:
    - Input: `pearls = Pearl(4)`
    - Execution: 
        - With only one pearl, no difference can be calculated.
    - Output: Could return infinity or another large value depending on the implementation.

6: E-valuate

Evaluate the performance of your algorithm and state any strong/weak or future potential work.

Time Complexity:

  • Time Complexity: O(N) where N is the number of nodes in the tree.
    • Explanation: We visit each node exactly once during the inorder traversal.

Space Complexity:

  • Space Complexity: O(H) where H is the height of the tree.
    • Explanation: The recursion stack will use space proportional to the height H of the tree. In a balanced tree, H is O(log N), but in the worst case (skewed tree), it could be O(N).
Fork me on GitHub