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 ifdogisTrue. Under"DOG_PERSON", a comment is directly unwanted ifcatisTrue. If bothcatanddogareTrue, the comment is unwanted in both modes. - A comment must be excluded if it is directly unwanted or if any ancestor along its
parent_commentchain is excluded. - If
parent_commentcontains an integer ID that does not appear anywhere incomments, treat the comment as a root-level post (the missing parent never causes exclusion on its own). - Ignore
bodycompletely; filtering depends solely oncat,dog,parent_comment, andmode. - 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
idincommentsis unique and satisfies0 <= id <= 10^9. - Each
parent_commentis eitherNoneor an integer in[0, 10^9]not equal to its ownid. - Following
parent_commentreferences never creates a cycle, though a single chain of replies may be up tolen(comments)levels deep. modeis guaranteed to be either"CAT_PERSON"or"DOG_PERSON".
Step-by-step walkthrough
Understand the reply trees and exclusion rules
Each comment record gives an
id, aparent_comment(Noneor another comment ID),body(ignored), and two booleanscatanddog. Because comments reply to earlier comments without cycles, they form a collection of reply trees:- A
"CAT_PERSON"avoids comments wheredogisTrue. - A
"DOG_PERSON"avoids comments wherecatisTrue. - 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_commentpoints to an ID that is missing fromcomments, treat the comment as top-level (the missing parent does not hide it).
Here is Example 3 in
"CAT_PERSON"mode (avoidingdog=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 hascat=True, dog=False, which a cat person normally wants to read, yet it is still excluded because its parent105was hidden. Sorting the hidden IDs{105, 112, 120, 108}in ascending order gives[105, 108, 112, 120].- A
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,000back-and-forth replies (0 <- 1 <- 2 <- ... <- 99,999) where none is undesired: - Comment1takes1step up, comment2takes2steps up, ..., comment99,999takes99,999steps up. - Total steps:1 + 2 + ... + 99,999, roughly5,000,000,000dictionary lookups—much too slow!Walking upward re-checks the same ancestors thousands of times. Walking downward from the top checks each comment once.
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_excludedstarts asFalse. Then we passcurrently_excludedstraight down to each of its direct replies! Oncecurrently_excludedflips toTrueat some comment,True or anythingstaysTruefor every reply, reply-to-reply, and deeper descendant beneath it. Every comment is visited once in O(n) time.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 incommentsbefore their parents, we build the tree in two separate passes:- Pass 1: Fill
by_id[comment["id"]] = commentfor all comments so we know the complete set of present IDs. - Pass 2: For each comment, check
parent_id = comment["parent_comment"]. Ifparent_id is Noneorparent_id not in by_id(a missing parent), addcomment_idtoroots. Otherwise appendcomment_idtochildren[parent_id].
Watch out for a classic Python trap: comment
0is a valid ID (0 <= id <= 10^9)! Writingif not parent_id:would treatparent_id == 0just likeNoneand detach every reply to comment0. Always testif 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)- Pass 1: Fill
Traverse with an explicit stack instead of recursion
Writing a recursive helper
dfs(comment_id, ancestor_excluded)looks clean, except Python limits recursion to roughly1,000nested calls by default—so a valid chain of100,000replies crashes withRecursionError.Replacing recursion with our own Python list
stackof(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 inby_id, every comment is pushed once and popped once—meaningexcludednever collects duplicate IDs. Sortingexcludedat 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 excludedTrace Example 3 step by step
In Example 3 (
mode = "CAT_PERSON", undesired meansdog=True),roots = [100]andchildren = {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]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
ncomments in O(n) dictionary insertions, Pass 2 inspectsnparent links in O(n), Pass 3 pushes and pops each of thencomments exactly once during DFS in O(n), and sorting thekexcluded IDs at the end takes O(k log k). - Space: O(n) extra memory.
by_idstoresnentries,rootsandchildrentogether holdncomment IDs across all lists,stackholds at mostnpairs on a wide tree, andexcludedholdsk <= nIDs.
Edge cases
- Empty
commentslist: Every pass does zero iterations and cleanly returns[]. - Missing parent ID: When
parent_commentis an integer not present inby_id(such as comment15replying to absent ID99in Example 1),parent_id not in by_idpromotes 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 at0, testingparent_id is None(rather thannot parent_id) ensures replies to comment0remain attached under0. - Replies appearing before their parents in
comments: Completingby_idin Pass 1 before checkingparent_id not in by_idin Pass 2 guarantees input order never misclassifies a reply as a root. - Both
cat=Trueanddog=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
stackwithout touching Python's recursion limit. - IDs up to
10^9: Stored in hash maps (dict) rather than array-indexed tables, keeping memory proportional toninstead of the maximum ID value.
Common mistakes
- Using recursive DFS on deep chains: Hits Python's
RecursionError(~1,000 frames) whenlen(comments)forms a single100,000-deep chain. - Writing
if not parent_id:instead ofif parent_id is None:: In Pythonbool(0)isFalse, detaching every reply to comment0and letting them escape exclusion when comment0is undesired. - Building
by_idandchildrenin a single pass: If reply30(withparent_comment=20) appears in the list before comment20,20is not inby_idyet, wrongly turning30into a top-level root. - Triggering a separate subtree traversal from every undesired node: If a chain has
50,000undesired comments stacked one under another, walking each subtree separately visits nodes repeatedly in O(n^2) time and produces duplicate IDs. - Parsing
bodyfor"cat"or"dog"substrings: The specification statesbodyis ignored; only the booleancatanddogfields determine filtering. - Returning IDs in traversal order without sorting: DFS visits subtrees in branch order (e.g., visiting child
108under120before sibling105), 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. Swappingstack.pop()forqueue.popleft()gives the exact same O(n + k log k) time and O(n) space, since visit order is erased byexcluded.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 hitNone, a missing ID, or an already-cached ancestor—and then fillingmemoalong the climbed path—also runs in O(n) time without buildingchildren, 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
Nbe the number of comments andk(k <= N) be the number of excluded comments. Buildingby_id, buildingrootsandchildren, 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
bis1when topicbis present—and run one user-independent O(N) top-down pass storingsubtree_topics[id] = subtree_topics[parent] | own_topics[id]. Then for any user with blocked-topics bitmaskB, commentidis 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'sparent_commenthas already arrived, its status isexcluded_by_mode[parent] or is_undesired(comment, mode)in O(1) time. If network reordering delivers a reply before its parent, park the reply inwaiting_children[parent_id](temporarily treating it as a root) and propagate exclusions downward throughwaiting_childrenas soon as the missing parent arrives.
Follow-up questions
- What are the asymptotic time and memory requirements of your algorithm for N comments?
- How would you adapt this filter if posts supported arbitrary topic tags and each user configured a custom blocklist?
- Suppose comments arrive one at a time over a live event stream, possibly out of order; how would you maintain excluded IDs incrementally?
Similar questions
- Straight-Line Word Search in a Character Grid
- Shortest Word Chain Under 1-to-2 Letter Substitutions
- Thread-Safe In-Memory Key-Value Cache with TTL
- Per-User Rolling-Window Rate Limiter
- Combine Overlapping Conversation Windows
- Community Moderator Seniority and Demotions
More Reddit interview questions
- Straight-Line Word Search in a Character Grid Medium
- Click-Through Rate Modeling and Evaluation Medium
- Configurable Single-Game Tennis Scorer Medium Pro
- Predicting Post Comment Probability at Feed-Ranking Scale Medium Pro
- Using AI Assistants Responsibly in Software Development Medium Pro
- Modeling and Mitigating Position Bias in Feed Ranking Hard Pro
- Feed Click-Through Rate Feature Engineering and Modeling Medium Pro
- Cross-Functional Partnership in Ads Data Science Easy Pro
- Governing a Feature Rollout Backed by Synthetic Control Hard Pro
- Justifying a Core Data Model Under Production Load Medium Pro