Codepath

Find Lonely Cichlids

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

Problem Highlights

  • 💡 Difficulty: Medium
  • Time to complete: 20-25 mins
  • 🛠️ Topics: Trees, Binary Trees, DFS (Depth-First Search)

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 tree where each node represents a cichlid.
  • What operation needs to be performed?
    • The function needs to find all "lonely" cichlids, which are nodes that are the only child of their parent.
  • What should be returned?
    • The function should return a list of values of all lonely cichlids.
HAPPY CASE
Input: family_1 = Cichlid('A', Cichlid('B', None, Cichlid('D')), Cichlid('C'))
Output: ['D']
Explanation: 'D' is the only lonely cichlid.

EDGE CASE
Input: family_3 = Cichlid('A', Cichlid('B', Cichlid('D', Cichlid('F', Cichlid('H')))), Cichlid('C', None, Cichlid('E', None, Cichlid('G', None, Cichlid('I')))))
Output: ['D', 'F', 'H', 'E', 'G', 'I']
Explanation: Multiple nodes are lonely in this more complex tree.

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 Tree problems, we want to consider the following approaches:

  • Tree Traversal: Use DFS (Depth-First Search) to explore all nodes and identify lonely nodes.
  • Recursive Helper Function: A helper function can traverse the tree and collect lonely nodes.

3: P-lan

Plan the solution with appropriate visualizations and pseudocode.

General Idea: Perform a depth-first traversal of the binary tree and check each node to see if it has only one child. If it does, add that child to the list of lonely cichlids.

1) If the tree is empty, return an empty list.
2) Initialize an empty list `lonely_cichlids` to store the lonely cichlids.
3) Define a helper function `dfs(node)` to perform the DFS:
    - If the node is `None`, return.
    - If the node has only one child, add that child to `lonely_cichlids`.
    - Recursively call `dfs` on both left and right children.
4) Call `dfs` starting from the root of the tree.
5) Return `lonely_cichlids`.

⚠️ Common Mistakes

  • Forgetting to account for nodes with no children.
  • Not handling cases where multiple lonely nodes exist in different parts of the tree.

4: I-mplement

Implement the code to solve the algorithm.

class Cichlid:
    def __init__(self, value, left=None, right=None):
        self.val = value
        self.left = left
        self.right = right

def find_lonely_cichlids(root):
    if not root:
        return []
    
    lonely_cichlids = []

    def dfs(node):
        if not node:
            return
        
        # Check if the node has only one child
        if node.left and not node.right:
            lonely_cichlids.append(node.left.val)
        elif not node.left and node.right:
            lonely_cichlids.append(node.right.val)
        
        # Continue searching in both subtrees
        dfs(node.left)
        dfs(node.right)
    
    # Start DFS from the root
    dfs(root)
    
    return lonely_cichlids

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: `family_1 = Cichlid('A', Cichlid('B', None, Cichlid('D')), Cichlid('C'))`
    - Execution: 
        - Start at root "A".
        - "B" has only one child "D".
        - Add "D" to the list of lonely cichlids.
    - Output: `['D']`
- Example 2:
    - Input: `family_2 = Cichlid('A', Cichlid('B', Cichlid('D')), Cichlid('C', Cichlid('E', Cichlid('F', None, Cichlid('G')))))`
    - Execution: 
        - Start at root "A".
        - "F" has only one child "G".
        - Add "G" to the list of lonely cichlids.
    - Output: `['D', 'G']`

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 traversal.
  • Space Complexity: O(H) where H is the height of the tree, due to the recursive call stack. In the worst case, this could be O(N) if the tree is skewed.
Fork me on GitHub