Filter Comment Subtrees by Pet Preference

Medium · Coding & Algorithms · Machine Learning Engineer · Onsite

Problem Statement

An online forum stores discussion threads as flat lists of comment records. Each comment either starts a new top-level thread (parent_comment is None) or replies directly to an earlier comment (parent_comment holds another comment's id), forming a forest of reply trees. Automated classifiers have already labeled every comment with two boolean flags—cat and dog—indicating whether the post mentions cats, dogs, both, or neither.

When rendering a page, a viewer selects one of two preference modes:

  • "CAT_PERSON" — hide every dog-related comment (dog == True).
  • "DOG_PERSON" — hide every cat-related comment (cat == True).

Collapsing an unwanted comment hides its entire reply subtree as well: whenever a comment is hidden, all direct and indirect replies beneath it at any nesting depth are also hidden, regardless of their own cat and dog flags.

Implement the function:

def get_comments_to_exclude(comments: list[dict], mode: str) -> list[int]:

Each dictionary in comments contains five keys:

Key Type Description
id int Unique non-negative integer identifier for the comment
parent_comment int or None id of the comment being replied to, or None if top-level
body str Raw text of the comment
cat bool True when tagged as cat-related
dog bool True when tagged as dog-related

The input list has no guaranteed ordering—a child reply may appear earlier in comments than the parent it references. Follow these exact filtering rules:

  • Under "CAT_PERSON", a comment is directly unwanted if dog is True. Under "DOG_PERSON", a comment is directly unwanted if cat is True. If both cat and dog are True, the comment is unwanted in both modes.
  • A comment must be excluded if it is directly unwanted or if any ancestor along its parent_comment chain is excluded.
  • If parent_comment contains an integer ID that does not appear anywhere in comments, treat the comment as a root-level post (the missing parent never causes exclusion on its own).
  • Ignore body completely; filtering depends solely on cat, dog, parent_comment, and mode.
  • Return the excluded comment IDs in strictly ascending numerical order with no duplicates, or [] if nothing is hidden.

Examples

Example 1

Input:
comments = [
    {"id": 0, "parent_comment": None, "body": "Weekend park photos", "cat": False, "dog": False},
    {"id": 15, "parent_comment": 99, "body": "Looks sunny out there", "cat": False, "dog": False},
    {"id": 4, "parent_comment": 0, "body": "Brought our terrier along", "cat": False, "dog": True},
    {"id": 8, "parent_comment": 0, "body": "Tabby stayed indoors", "cat": True, "dog": False}
]
mode = "CAT_PERSON"

Output: [4]

Explanation: In "CAT_PERSON" mode, dog == True triggers exclusion. Comment 0 is kept (dog is False), reply 8 is kept (dog is False), and reply 4 is excluded (dog is True). Comment 15 points to parent_comment = 99, which is absent from comments, so 15 acts as a top-level comment and stays visible.

Example 2

Input:
comments = [
    {"id": 30, "parent_comment": 20, "body": "Count me in", "cat": False, "dog": False},
    {"id": 10, "parent_comment": None, "body": "Kitten adoption thread", "cat": True, "dog": False},
    {"id": 40, "parent_comment": 30, "body": "Which shelter?", "cat": False, "dog": False},
    {"id": 20, "parent_comment": 10, "body": "Sharing with friends", "cat": False, "dog": False},
    {"id": 25, "parent_comment": None, "body": "Golden retriever meetup", "cat": False, "dog": True}
]
mode = "DOG_PERSON"

Output: [10, 20, 30, 40]

Explanation: Even though replies 30, 40, and 20 appear out of order, they form the chain 10 -> 20 -> 30 -> 40. Under "DOG_PERSON", root 10 (cat == True) is hidden, which cascades to 20, 30, and 40 despite their False flags. Root 25 (cat == False) remains visible.

Example 3

Input:
comments = [
    {"id": 108, "parent_comment": 120, "body": "Lucky you", "cat": False, "dog": False},
    {"id": 112, "parent_comment": 105, "body": "Haha my Siamese tries that too", "cat": True, "dog": False},
    {"id": 100, "parent_comment": None, "body": "Favorite pet stories?", "cat": False, "dog": False},
    {"id": 120, "parent_comment": 102, "body": "Both our pug and calico are asleep", "cat": True, "dog": True},
    {"id": 105, "parent_comment": 100, "body": "Beagle stole my sandwich", "cat": False, "dog": True},
    {"id": 102, "parent_comment": 100, "body": "Quiet morning here", "cat": False, "dog": False}
]
mode = "CAT_PERSON"

Output: [105, 108, 112, 120]

Explanation: Under "CAT_PERSON", comments 105 (dog == True) and 120 (cat == True, dog == True) are directly unwanted. Reply 112 is purely about cats (cat == True, dog == False), yet it is still hidden because its parent 105 was hidden. Reply 108 is hidden under 120. Sorting {105, 112, 120, 108} ascending produces [105, 108, 112, 120].

Constraints

  • 0 <= len(comments) <= 100,000
  • Every id in comments is unique and satisfies 0 <= id <= 10^9.
  • Each parent_comment is either None or an integer in [0, 10^9] not equal to its own id.
  • Following parent_comment references never creates a cycle, though a single chain of replies may be up to len(comments) levels deep.
  • mode is guaranteed to be either "CAT_PERSON" or "DOG_PERSON".

Step-by-step walkthrough

  1. Understand the reply trees and exclusion rules

    Each comment record gives an id, a parent_comment (None or another comment ID), body (ignored), and two booleans cat and dog. Because comments reply to earlier comments without cycles, they form a collection of reply trees:

    • A "CAT_PERSON" avoids comments where dog is True.
    • A "DOG_PERSON" avoids comments where cat is True.
    • Hiding a comment also hides its entire subtree of replies at every depth—even if a reply talks about the animal the reader likes!
    • If parent_comment points to an ID that is missing from comments, treat the comment as top-level (the missing parent does not hide it).

    Here is Example 3 in "CAT_PERSON" mode (avoiding dog=True):

                      100 (cat=F, dog=F)
                     /                  \
          105 (cat=F, dog=T) [HIDE]    102 (cat=F, dog=F)
                   |                            |
          112 (cat=T, dog=F) [HIDE]    120 (cat=T, dog=T) [HIDE]
                                                |
                                       108 (cat=F, dog=F) [HIDE]
    

    Notice comment 112: it has cat=True, dog=False, which a cat person normally wants to read, yet it is still excluded because its parent 105 was hidden. Sorting the hidden IDs {105, 112, 120, 108} in ascending order gives [105, 108, 112, 120].

  2. Why walking upward from every comment can be O(n^2)

    A tempting first draft indexes comments by ID, then starts at each comment and walks upward (parent_comment -> parent's parent -> ...) until it either finds an undesired comment or reaches the top.

    That produces the right answer, but think about a single thread of 100,000 back-and-forth replies (0 <- 1 <- 2 <- ... <- 99,999) where none is undesired: - Comment 1 takes 1 step up, comment 2 takes 2 steps up, ..., comment 99,999 takes 99,999 steps up. - Total steps: 1 + 2 + ... + 99,999, roughly 5,000,000,000 dictionary lookups—much too slow!

    Walking upward re-checks the same ancestors thousands of times. Walking downward from the top checks each comment once.

  3. Key insight: push one boolean downward from the roots

    Whether a comment should be hidden depends on just two booleans: 1. Was any ancestor above it already hidden (ancestor_excluded)? 2. Is this comment itself undesired (is_undesired(comment, mode))?

    currently_excluded = ancestor_excluded or is_undesired(comment, mode)
    

    For a top-level comment, ancestor_excluded starts as False. Then we pass currently_excluded straight down to each of its direct replies! Once currently_excluded flips to True at some comment, True or anything stays True for every reply, reply-to-reply, and deeper descendant beneath it. Every comment is visited once in O(n) time.

  4. Build the comment lookup table and parent-to-replies map

    The input gives upward pointers (parent_comment), whereas walking top-down requires downward pointers (children[parent_id] = [reply_ids...]). Because replies can appear in comments before their parents, we build the tree in two separate passes:

    1. Pass 1: Fill by_id[comment["id"]] = comment for all comments so we know the complete set of present IDs.
    2. Pass 2: For each comment, check parent_id = comment["parent_comment"]. If parent_id is None or parent_id not in by_id (a missing parent), add comment_id to roots. Otherwise append comment_id to children[parent_id].

    Watch out for a classic Python trap: comment 0 is a valid ID (0 <= id <= 10^9)! Writing if not parent_id: would treat parent_id == 0 just like None and detach every reply to comment 0. Always test if parent_id is None:.

    def is_undesired(comment: dict, mode: str) -> bool:
        """Return True when this comment's own flags match the animal the reader avoids."""
        if mode == "CAT_PERSON":
            return comment["dog"]
        return comment["cat"]
    
    
    def get_comments_to_exclude(comments: list[dict], mode: str) -> list[int]:
        # Phase 1: Index every comment by ID first because a reply can appear
        # earlier in `comments` than its parent.
        # by_id: {comment_id: comment_dict}, e.g. {1: {"id": 1, ...}, 2: {"id": 2, ...}}
        by_id: dict[int, dict] = {}
        for comment in comments:
            by_id[comment["id"]] = comment
    
        # Phase 2: Build downward reply links and find all tree roots.
        # children: {parent_id: [reply_id, ...]}, e.g. {1: [2, 4], 2: [3]}
        # roots: list of top-level comment IDs (parent is None or absent from input)
        children: dict[int, list[int]] = {}
        roots: list[int] = []
        for comment in comments:
            comment_id = comment["id"]
            parent_id = comment["parent_comment"]
    
            # Check `parent_id is None` explicitly (not `not parent_id`) because 0 is a valid ID!
            if parent_id is None or parent_id not in by_id:
                roots.append(comment_id)
            else:
                if parent_id not in children:
                    children[parent_id] = []
                children[parent_id].append(comment_id)
    
  5. Traverse with an explicit stack instead of recursion

    Writing a recursive helper dfs(comment_id, ancestor_excluded) looks clean, except Python limits recursion to roughly 1,000 nested calls by default—so a valid chain of 100,000 replies crashes with RecursionError.

    Replacing recursion with our own Python list stack of (comment_id, ancestor_excluded) pairs runs in heap memory with no depth limit at all. Because each comment lives under a single root and has at most one parent in by_id, every comment is pushed once and popped once—meaning excluded never collects duplicate IDs. Sorting excluded at the end puts the IDs in ascending order.

        # Phase 3: Iterative depth-first search from every root.
        # Using an explicit list stack avoids Python's ~1,000-frame recursion limit
        # when a reply chain is up to 100,000 comments deep.
        # stack: list of (comment_id, ancestor_excluded) pairs.
        excluded: list[int] = []
        stack: list[tuple[int, bool]] = []
        for root_id in roots:
            stack.append((root_id, False))
    
        while stack:
            comment_id, ancestor_excluded = stack.pop()
            # Once any ancestor is excluded, every descendant is excluded regardless of its own flags.
            currently_excluded = ancestor_excluded or is_undesired(by_id[comment_id], mode)
            if currently_excluded:
                excluded.append(comment_id)
    
            for reply_id in children.get(comment_id, []):
                stack.append((reply_id, currently_excluded))
    
        # Phase 4: Tree traversal visits IDs out of numeric order, so sort ascending.
        excluded.sort()
        return excluded
    
  6. Trace Example 3 step by step

    In Example 3 (mode = "CAT_PERSON", undesired means dog=True), roots = [100] and children = {100: [105, 102], 105: [112], 102: [120], 120: [108]}:

    Popped pair    dog flag   currently_excluded   Pushed to stack              excluded list
    ------------   --------   ------------------   --------------------------   ----------------------
    (100, False)   False      False                (105, False), (102, False)   []
    (102, False)   False      False                (120, False)                 []
    (120, False)   True       True                 (108, True)                  [120]
    (108, True)    False      True (from parent)   (none)                       [120, 108]
    (105, False)   True       True                 (112, True)                  [120, 108, 105]
    (112, True)    False      True (from parent)   (none)                       [120, 108, 105, 112]
    
    After excluded.sort() -> [105, 108, 112, 120]
    
  7. Complete solution

    from typing import Any, Dict, List, Optional, Set, Tuple
    
    
    def is_undesired(comment: dict, mode: str) -> bool:
        """Return True when this comment's own flags match the animal the reader avoids."""
        if mode == "CAT_PERSON":
            return comment["dog"]
        return comment["cat"]
    
    
    def get_comments_to_exclude(comments: list[dict], mode: str) -> list[int]:
        # Phase 1: Index every comment by ID first because a reply can appear
        # earlier in `comments` than its parent.
        # by_id: {comment_id: comment_dict}, e.g. {1: {"id": 1, ...}, 2: {"id": 2, ...}}
        by_id: dict[int, dict] = {}
        for comment in comments:
            by_id[comment["id"]] = comment
    
        # Phase 2: Build downward reply links and find all tree roots.
        # children: {parent_id: [reply_id, ...]}, e.g. {1: [2, 4], 2: [3]}
        # roots: list of top-level comment IDs (parent is None or absent from input)
        children: dict[int, list[int]] = {}
        roots: list[int] = []
        for comment in comments:
            comment_id = comment["id"]
            parent_id = comment["parent_comment"]
    
            # Check `parent_id is None` explicitly (not `not parent_id`) because 0 is a valid ID!
            if parent_id is None or parent_id not in by_id:
                roots.append(comment_id)
            else:
                if parent_id not in children:
                    children[parent_id] = []
                children[parent_id].append(comment_id)
    
        # Phase 3: Iterative depth-first search from every root.
        # Using an explicit list stack avoids Python's ~1,000-frame recursion limit
        # when a reply chain is up to 100,000 comments deep.
        # stack: list of (comment_id, ancestor_excluded) pairs.
        excluded: list[int] = []
        stack: list[tuple[int, bool]] = []
        for root_id in roots:
            stack.append((root_id, False))
    
        while stack:
            comment_id, ancestor_excluded = stack.pop()
            # Once any ancestor is excluded, every descendant is excluded regardless of its own flags.
            currently_excluded = ancestor_excluded or is_undesired(by_id[comment_id], mode)
            if currently_excluded:
                excluded.append(comment_id)
    
            for reply_id in children.get(comment_id, []):
                stack.append((reply_id, currently_excluded))
    
        # Phase 4: Tree traversal visits IDs out of numeric order, so sort ascending.
        excluded.sort()
        return excluded
    

    ✅ Submit now — all tests should pass.

Intuition & how it works

Think of collapsing a comment on an online discussion forum: the moment you collapse a comment, that comment and every nested reply underneath it vanish from the page together, regardless of what the nested replies say. Our comments form a forest—a collection of independent trees (hierarchies where each item has at most one parent and no loops). In tree terminology, any comment along the chain of parents above you is an ancestor, and any reply nested at any level below you is a descendant.

Why does the naive approach fall short? If you start at each comment and walk up its parent_comment links looking for an undesired ancestor, a single reply chain of 100,000 comments forces you to walk 1 + 2 + ... + 99,999 links—roughly 5 billion steps (O(n^2) time). Flipping the direction from bottom-up to top-down eliminates all repeated work: you start at the top-level roots and pass a single ancestor_excluded boolean down to each child, visiting every comment once.

To explore each tree from top to bottom, we use depth-first search (DFS)—an algorithm that follows a branch down through its children using a last-in, first-out stack before moving to the next sibling branch. Crucially, we manage our own stack list instead of writing a recursive function, because Python's call stack (the internal memory tracking nested function calls) raises RecursionError around 1,000 levels deep, whereas a thread here can reach 100,000 levels.

Let's trace a tiny example in "CAT_PERSON" mode (where dog=True is undesired): - Comment 100 (parent=None, cat=F, dog=F) has reply 105 (parent=100, cat=F, dog=T), which has reply 112 (parent=105, cat=T, dog=F). - Root 100 pops as (100, False): dog is False, so currently_excluded = False, and it pushes (105, False). - Reply 105 pops as (105, False): dog is True, so currently_excluded = True (105 is recorded), and it pushes (112, True). - Reply 112 pops as (112, True): even though dog is False and cat is True, ancestor_excluded is already True, so 112 is also recorded—returning [105, 112].

Complexity

Let n be the total number of comments and k be the number of excluded comments (0 <= k <= n).

  • Time: O(n + k log k), which is O(n log n) in the worst case when a constant fraction of comments are excluded. Pass 1 indexes n comments in O(n) dictionary insertions, Pass 2 inspects n parent links in O(n), Pass 3 pushes and pops each of the n comments exactly once during DFS in O(n), and sorting the k excluded IDs at the end takes O(k log k).
  • Space: O(n) extra memory. by_id stores n entries, roots and children together hold n comment IDs across all lists, stack holds at most n pairs on a wide tree, and excluded holds k <= n IDs.

Edge cases

  • Empty comments list: Every pass does zero iterations and cleanly returns [].
  • Missing parent ID: When parent_comment is an integer not present in by_id (such as comment 15 replying to absent ID 99 in Example 1), parent_id not in by_id promotes it to a root so the missing parent causes no exclusion while the comment's own flags still apply.
  • Parent ID equal to 0: Because IDs start at 0, testing parent_id is None (rather than not parent_id) ensures replies to comment 0 remain attached under 0.
  • Replies appearing before their parents in comments: Completing by_id in Pass 1 before checking parent_id not in by_id in Pass 2 guarantees input order never misclassifies a reply as a root.
  • Both cat=True and dog=True: Excluded in both "CAT_PERSON" and "DOG_PERSON" modes, along with all descendants.
  • Undesired reply nested under an already-excluded ancestor: Because DFS visits each tree node once, its ID is appended once—never duplicated.
  • 100,000-deep linear reply chain: Handled safely in heap memory by the iterative stack without touching Python's recursion limit.
  • IDs up to 10^9: Stored in hash maps (dict) rather than array-indexed tables, keeping memory proportional to n instead of the maximum ID value.

Common mistakes

  • Using recursive DFS on deep chains: Hits Python's RecursionError (~1,000 frames) when len(comments) forms a single 100,000-deep chain.
  • Writing if not parent_id: instead of if parent_id is None:: In Python bool(0) is False, detaching every reply to comment 0 and letting them escape exclusion when comment 0 is undesired.
  • Building by_id and children in a single pass: If reply 30 (with parent_comment=20) appears in the list before comment 20, 20 is not in by_id yet, wrongly turning 30 into a top-level root.
  • Triggering a separate subtree traversal from every undesired node: If a chain has 50,000 undesired comments stacked one under another, walking each subtree separately visits nodes repeatedly in O(n^2) time and produces duplicate IDs.
  • Parsing body for "cat" or "dog" substrings: The specification states body is ignored; only the boolean cat and dog fields determine filtering.
  • Returning IDs in traversal order without sorting: DFS visits subtrees in branch order (e.g., visiting child 108 under 120 before sibling 105), whereas the specification requires strictly ascending IDs.

Alternative approaches

  • Iterative breadth-first search (BFS): Breadth-first search explores a tree level by level using a first-in, first-out queue (collections.deque) instead of a stack. Swapping stack.pop() for queue.popleft() gives the exact same O(n + k log k) time and O(n) space, since visit order is erased by excluded.sort().
  • Bottom-up parent climbing with memoization: Memoization means caching each node's computed result in a dictionary (memo[id] = True/False) so you never recompute it. Climbing up from each comment until you hit None, a missing ID, or an already-cached ancestor—and then filling memo along the climbed path—also runs in O(n) time without building children, though managing path write-backs iteratively takes slightly more bookkeeping than top-down DFS.

Follow-up questions

  • What are the asymptotic time and memory requirements of your algorithm for N comments? Let N be the number of comments and k (k <= N) be the number of excluded comments. Building by_id, building roots and children, and running iterative DFS each visit every comment a constant number of times in O(N) time, while sorting the output takes O(k log k) time—for O(N + k log k) total time (O(N log N) worst case, or O(N) if unsorted output were permitted) and O(N) auxiliary memory.
  • How would you adapt this filter if posts supported arbitrary topic tags and each user configured a custom blocklist? Represent a set of topics as a bitmask—an integer where bit b is 1 when topic b is present—and run one user-independent O(N) top-down pass storing subtree_topics[id] = subtree_topics[parent] | own_topics[id]. Then for any user with blocked-topics bitmask B, comment id is excluded if and only if (subtree_topics[id] & B) != 0, answering per-user queries with a single bitwise AND per comment.
  • Suppose comments arrive one at a time over a live event stream, possibly out of order; how would you maintain excluded IDs incrementally? Maintain excluded_by_mode[id] as comments arrive: when a new comment's parent_comment has already arrived, its status is excluded_by_mode[parent] or is_undesired(comment, mode) in O(1) time. If network reordering delivers a reply before its parent, park the reply in waiting_children[parent_id] (temporarily treating it as a root) and propagate exclusions downward through waiting_children as soon as the missing parent arrives.

Follow-up questions

Similar questions

More Reddit interview questions

All 36 Reddit questions →