Codepath

Sorting Pearls by 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 the size of a pearl.
  • What operation needs to be performed?
    • The function needs to traverse the BST and return a sorted list of pearl sizes from smallest to largest.
  • What should be returned?
    • The function should return a list of pearl sizes sorted in ascending order.
HAPPY CASE
Input: pearls = Pearl(3, Pearl(1, None, Pearl(2)), Pearl(5, Pearl(4), Pearl(8)))
Output: [1, 2, 3, 4, 5, 8]
Explanation: The pearls are sorted in ascending order using an inorder traversal.

EDGE CASE
Input: pearls = 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: An inorder traversal of a BST returns the nodes in sorted order by value.
  • Iterative Traversal: Implement an iterative inorder traversal using a stack to simulate the recursion stack.

3: P-lan

Plan the solution with appropriate visualizations and pseudocode.

General Idea (Iterative Approach): Use a stack to perform an iterative inorder traversal, which simulates the recursive process of visiting nodes in the correct order.

1) Initialize an empty list `sorted_list` to store the sorted pearl sizes.
2) Initialize an empty stack and set `current` to the root of the tree (`pearls`).
3) While `current` is not `None` or the stack is not empty:
    - Traverse the left subtree by pushing nodes onto the stack.
    - Pop the top node from the stack, add its value to `sorted_list`.
    - Set `current` to the right child of the popped node.
4) Return `sorted_list`.

⚠️ Common Mistakes

  • Not correctly handling the case where the tree is empty.
  • Forgetting to move to the right subtree after processing the current node.

4: I-mplement

Implement the code to solve the algorithm.

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

def smallest_to_largest_iterative(pearls):
    sorted_list = []
    stack = []
    current = pearls
    
    while current or stack:
        # Go as left as possible
        while current:
            stack.append(current)
            current = current.left
        
        # Process the node
        current = stack.pop()
        sorted_list.append(current.val)
        
        # Move to the right subtree
        current = current.right
    
    return sorted_list

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(3, Pearl(1, None, Pearl(2)), Pearl(5, Pearl(4), Pearl(8)))`
    - Execution: 
        - Perform iterative inorder traversal.
        - Visit nodes in the order 1 -> 2 -> 3 -> 4 -> 5 -> 8.
    - Output: `[1, 2, 3, 4, 5, 8]`
- Example 2:
    - Input: `pearls = None`
    - Execution: The tree is empty, so return an empty list.
    - Output: `[]`

6: E-valuate

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

Time Complexity:

  • Recursive Solution (smallest_to_largest_recursive): O(N)

    • Explanation: We visit each of the N nodes exactly once during the traversal.
  • Iterative Solution (smallest_to_largest_iterative): O(N)

    • Explanation: Similarly, we visit each of the N nodes exactly once, and the stack operations (push and pop) are performed N times.

Space Complexity:

  • Recursive Solution (smallest_to_largest_recursive): O(H)

    • 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).
  • Iterative Solution (smallest_to_largest_iterative): O(H)

    • Explanation: The stack will hold at most H nodes at any time, where H is the height of the tree. In a balanced tree, H is O(log N), and in the worst case, it could be O(N).
Fork me on GitHub