Hide Flagged Comment Threads for a Pet-Preference Reader
Trees & GraphsAuto-graded · 28 test casesLast updated
Find all comments hidden from a reader when any flagged comment hides its whole reply subtree, handling unordered input, dangling parent IDs, and very deep chains.
A discussion thread is stored as a flat list of comment records. Each comment is either a reply to another comment (its parent) or a top-level comment, so together the comments form a forest of reply trees. Every comment also has two boolean flags telling whether it talks about cats and whether it talks about dogs.
A reader browses in one of two modes:
"CAT_PERSON": the reader wants to avoid anything about dogs."DOG_PERSON": the reader wants to avoid anything about cats.
When a comment mentions the animal the reader wants to avoid, that comment is hidden together with every reply beneath it, at any depth. Your task is to return the IDs of all hidden comments.
Input
comments is a list of dictionaries with these keys:
| Key | Type | Meaning |
|---|---|---|
id | int | Unique comment ID |
parent_comment | int or None | ID of the comment being replied to, or None if top-level |
body | str | Comment text |
cat | bool | The comment is about cats |
dog | bool | The comment is about dogs |
The list may be in any order. A reply can appear before the comment it replies to.
mode is a string, either "CAT_PERSON" or "DOG_PERSON".
Rules
- In
"CAT_PERSON"mode, a comment is unwanted if itsdogflag isTrue. In"DOG_PERSON"mode, a comment is unwanted if itscatflag isTrue. A comment with both flags set is unwanted in both modes. - A comment is hidden if it is unwanted, or if any ancestor (parent, grandparent, and so on) is unwanted. Once an ancestor is unwanted, the comment's own flags are irrelevant.
- If
parent_commentholds an ID that is not present incomments, treat that comment as top-level. The missing parent never causes a comment to be hidden. - The
bodytext has no influence on the result. - Return the hidden IDs sorted in ascending order, with no duplicates. If nothing is hidden, return
[].
Constraints
0 <= len(comments) <= 100000- IDs are distinct integers with
0 <= id <= 10^9. parent_commentisNoneor an integer in the same range; it never equals the comment's ownid, and following parent links never forms a cycle.- A chain of replies can be as long as the total number of comments.
modeis exactly"CAT_PERSON"or"DOG_PERSON".
Examples
Example 1
Input: find_hidden_comments([{'id': 0, 'parent_comment': None, 'body': 'Look! A cute baby elephant taking a nap!', 'cat': False, 'dog': False}, {'id': 2, 'parent_comment': 1, 'body': 'I agree!', 'cat': False, 'dog': False}, {'id': 11, 'parent_comment': 0, 'body': 'Almost as cute as my poodle!', 'cat': False, 'dog': True}], 'CAT_PERSON')
Output: [11]
Example 2
Input: find_hidden_comments([{'id': 5, 'parent_comment': None, 'body': 'My puppy learned to sit today', 'cat': False, 'dog': True}, {'id': 6, 'parent_comment': 5, 'body': 'Congratulations!', 'cat': False, 'dog': False}, {'id': 7, 'parent_comment': 6, 'body': 'Thanks!', 'cat': False, 'dog': False}, {'id': 8, 'parent_comment': 7, 'body': 'Any training tips?', 'cat': False, 'dog': False}, {'id': 9, 'parent_comment': None, 'body': 'My cat ignores every command', 'cat': True, 'dog': False}], 'CAT_PERSON')
Output: [5, 6, 7, 8]
Example 3
Input: find_hidden_comments([{'id': 6, 'parent_comment': 5, 'body': 'Same here', 'cat': False, 'dog': False}, {'id': 3, 'parent_comment': 2, 'body': 'My dog does that too', 'cat': False, 'dog': True}, {'id': 1, 'parent_comment': None, 'body': 'What do your pets do all day?', 'cat': False, 'dog': False}, {'id': 5, 'parent_comment': 4, 'body': 'My cat and my dog nap together', 'cat': True, 'dog': True}, {'id': 2, 'parent_comment': 1, 'body': 'My cat sleeps on the keyboard', 'cat': True, 'dog': False}, {'id': 4, 'parent_comment': 1, 'body': 'Mostly sleeping, I assume', 'cat': False, 'dog': False}], 'DOG_PERSON')
Output: [2, 3, 5, 6]
Hints
Hint 1
Hiding spreads from a parent to its replies, so think of the result as the union of whole subtrees rooted at each unwanted comment.
Hint 2
Building a map from parent ID to the list of child IDs lets you walk downward from unwanted comments instead of repeatedly climbing up ancestor chains, which would be quadratic on a long chain.
Hint 3
Only register a child under a parent that actually exists in the input, and use an explicit stack rather than recursion because the reply chain can be 100,000 deep.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Hiding propagates from a comment to all of its descendants, so the set of hidden comments is exactly the union of the subtrees rooted at every unwanted comment.
- Pick the flag to check:
dogfor"CAT_PERSON",catfor"DOG_PERSON". - Collect all IDs present in the input.
- Build a map from parent ID to child IDs, adding an edge only when the parent ID exists in the input. A comment whose parent is missing therefore behaves as a top-level comment.
- Seed a stack with every unwanted comment.
- Run an iterative DFS downward from the seeds, marking each reached comment as hidden and skipping ones already hidden.
- Return the hidden IDs sorted.
Why it is correct
- Everything required is reached. If comment
xmust be hidden, some commentuon its path to the root (possiblyxitself) is unwanted. All links on the path fromutoxpoint to existing comments, so those edges are in the child map, and the DFS started atureachesx. - Nothing extra is reached. The DFS only follows child edges from unwanted comments, so every visited comment is unwanted or a descendant of an unwanted one.
- Missing parents are harmless. No edge is created for them, so nothing propagates through them.
- Own flags don't matter under a hidden ancestor. The DFS adds descendants regardless of their flags.
- Duplicates. An unwanted comment under another unwanted comment is reached twice, but the
hiddenset ensures it is expanded once. - Deep chains. An explicit stack avoids Python's recursion limit.
Walking upward from every comment would cost O(depth) each, which is quadratic on a long chain; pushing hiding downward avoids this.
Complexity
With n comments:
- Time: O(n) for building the structures and traversing (each comment is expanded once and each edge examined once), plus O(k log k) for sorting the
khidden IDs, so O(n log n) overall. - Space: O(n) for the ID set, child map, stack, and hidden set.
Reference solution
def find_hidden_comments(comments: list[dict], mode: str) -> list[int]:
# Flag that marks a comment as unwanted for this reader.
flag = "dog" if mode == "CAT_PERSON" else "cat"
present = {c["id"] for c in comments}
# Map each existing parent ID to its child IDs.
children = {}
for c in comments:
p = c["parent_comment"]
if p is not None and p in present:
children.setdefault(p, []).append(c["id"])
# Every unwanted comment is the root of a hidden subtree.
stack = [c["id"] for c in comments if c[flag]]
hidden = set()
while stack:
node = stack.pop()
if node in hidden:
continue
hidden.add(node)
for child in children.get(node, ()):
if child not in hidden:
stack.append(child)
return sorted(hidden)