Sortable and Filterable Nested Comment Threads
Medium · Coding & Algorithms · Software Engineer · Technical Screen
Problem Statement
A client application receives a flat list of discussion records in memory and must organize them into a sortable, searchable thread hierarchy without any server-side changes. Every raw comment dictionary has five keys:
id: unique identifier for the commentuserId: identifier of the author who posted ittimestamp: creation instant, given either as an ISO 8601 string (with"Z", an explicit UTC offset such as"+02:00", or no offset—which is interpreted as UTC) or as a numeric Unix epoch value (intorfloat). A helperparse_timestamp(value)is already provided.content: body text of the commentparentId:idof the comment it replies to, orNonefor a top-level post
Implement the client-side data helpers and stateful controller defined in starter.py:
sort_comments(comments, field="timestamp", direction="desc")— Return a new list ordered byfield("timestamp"comparing parsed instants, or"userId") indirection("asc"or"desc"), without mutatingcomments. RaiseValueErrorfor any otherfieldordirection. Whenever two comments tie on the primary sort key, order the oldertimestampfirst and then the smalleridfirst in both"asc"and"desc"modes.save_sort_preference(storage, field, direction)&load_sort_preference(storage)— Persist and restore the user's sort setting instorage(aMutableMapping[str, str]modeling browserlocalStorage, where keys and values are strings) underSTORAGE_KEY = "comments.sort".save_sort_preferenceraisesValueErroron invalid choices;load_sort_preferencereturnsDEFAULT_SORT = ("timestamp", "desc")whenever nothing is stored or the stored string is malformed or unsupported.build_tree(comments, field="timestamp", direction="desc")— Assemble a nested forest from flatparentIdlinks without mutating input dictionaries. Each tree node is a copy of its comment dictionary plus"children": [...]. Both the returned root list and every"children"list must followsort_commentsorder. Any comment whoseparentIdisNone, equals its ownid, or does not match any comment incommentsis placed at the root level.filter_comments(comments, query)— Trim surrounding whitespace fromquery; if blank, return a shallow copy ofcomments. Otherwise matchquerycase-insensitively as a substring ofcontentand return every matching comment plus all of its descendants at any reply depth, preserving input order and omitting unrelated branches.CommentView(comments, storage)— Coordinate the UI state:__init__(comments, storage)copiescomments, loads(self.field, self.direction)fromstorage, and setsself.query = "".set_sort(field, direction)validates and saves the new preference tostoragebefore updatingself.fieldandself.direction.set_filter(query)updatesself.queryin memory only (filter text is not persisted across refreshes).visible_tree()filtersself.commentsbyself.queryand builds the sorted tree using(self.field, self.direction).
Examples
Example 1
Input:
comments = [
{"id": 10, "userId": 200, "timestamp": "2025-03-15T14:00:00Z", "content": "Index reduced query latency", "parentId": None},
{"id": 20, "userId": 100, "timestamp": "2025-03-15T14:06:00Z", "content": "Watch write amplification on inserts", "parentId": 10},
{"id": 30, "userId": 300, "timestamp": "2025-03-15T14:12:00Z", "content": "Good catch, benchmarked bulk loads", "parentId": 20},
{"id": 40, "userId": 200, "timestamp": "2025-03-15T13:15:00Z", "content": "Deploy window moved to Friday", "parentId": None},
{"id": 50, "userId": 100, "timestamp": "2025-03-15T14:03:00Z", "content": "Composite index helped dashboard too", "parentId": 10},
{"id": 60, "userId": 300, "timestamp": "2025-03-15T13:45:00Z", "content": "Acknowledged by on-call", "parentId": 40},
]
storage = {}
view = CommentView(comments, storage)
default_roots = [node["id"] for node in view.visible_tree()]
view.set_sort("userId", "asc")
refreshed = CommentView(comments, storage)
Output:
default_roots == [10, 40]
# Under default ("timestamp", "desc"):
# 10 -> children [20 -> children [30], 50]
# 40 -> children [60]
(refreshed.field, refreshed.direction) == ("userId", "asc")
# Under ("userId", "asc"), roots 40 and 10 share userId 200 so older 40 (13:15) precedes 10 (14:00);
# under 10, replies 50 (14:03) and 20 (14:06) share userId 100 so older 50 precedes 20:
# 40 -> children [60]
# 10 -> children [50, 20 -> children [30]]
Explanation: With empty storage, view defaults to ("timestamp", "desc"), placing newer root 10 (14:00) ahead of 40 (13:15) and newer reply 20 (14:06) ahead of 50 (14:03). Calling set_sort("userId", "asc") serializes the choice into storage["comments.sort"], so constructing refreshed on the same storage restores ("userId", "asc") and resolves equal-userId ties older-first.
Example 2
Input:
# Using the same 6-comment list from Example 1:
view = CommentView(comments, {})
view.set_filter("AMPLIFICATION")
filtered_tree = view.visible_tree()
Output:
[c["id"] for c in filter_comments(comments, "AMPLIFICATION")] == [20, 30]
# filtered_tree has a single root 20 with child 30:
# 20 -> children [30]
Explanation: Case-insensitive matching on "AMPLIFICATION" hits comment 20 ("Watch write amplification on inserts"). Its descendant 30 is automatically retained even though 30's own text does not contain "amplification", whereas non-matching ancestor 10, sibling 50, and unrelated thread 40 -> 60 are excluded. Because 20's parentId (10) is absent from the filtered subset, build_tree promotes 20 to a top-level root with 30 nested beneath it.
Constraints
0 <= len(comments) <= 10^4- Every
comment["id"]in a single input list is unique and comparable (intorstr);userIdvalues are mutually comparable. timestampis either anint/floatepoch value or a valid ISO 8601 datetime string.storageonly storesstrkeys andstrvalues, and may initially contain missing, malformed, or outdated JSON text underSTORAGE_KEY.- Input lists and individual comment dictionaries passed by callers must never be mutated in place.
Step-by-step walkthrough
Understand the data shapes and pipeline order
We have a flat list of discussion records in memory and need four client-side capabilities without modifying any backend endpoint: 1. Order records by
timestamporuserIdin ascending ("asc") or descending ("desc") mode. 2. Persist the chosen sort setting so reloading the page restores it. 3. Assemble nested reply trees from flatparentIdlinks. 4. Filtercontentcase-insensitively so every matching comment along with all of its descendants stays visible while unrelated threads are hidden.Before writing code, define the three data shapes and the pipeline order:
- Flat comment (
Comment):{"id": 10, "userId": 200, "timestamp": "2025-03-15T14:00:00Z", "content": "...", "parentId": None}. Top-level posts haveparentId: None. - Browser storage (
storage): a string-to-string mapping modelingwindow.localStoragein the browser. - Tree node: a shallow copy of a comment dictionary with one added key,
"children": [...], holding its nested reply nodes. Copying avoids mutating the caller's input dictionaries.
Running filtering before tree construction makes orphan promotion fall out naturally:
flat comments | v filter_comments(comments, query) visible flat subset (matching comments + all their descendants) | v build_tree(shown_comments, field, direction) sorted nested forest ready to renderWhy filter before building the tree? Suppose comment
20matches the search query while its parent comment10does not. Afterfilter_comments,20and its reply30remain in the visible list while10is excluded. Whenbuild_treesees that20'sparentId(10) is absent from the visible dictionary, it automatically promotes20(with30nested beneath it) to a top-level root!from typing import Any, Dict, List, MutableMapping, Tuple import json from datetime import datetime, timezone # Each raw comment dictionary has shape: # {"id": 10, "userId": 200, "timestamp": "2025-03-15T14:00:00Z", "content": "...", "parentId": None} Comment = Dict[str, Any] SORT_FIELDS = ("timestamp", "userId") SORT_DIRECTIONS = ("asc", "desc") DEFAULT_SORT = ("timestamp", "desc") # newest first when nothing valid is saved STORAGE_KEY = "comments.sort"- Flat comment (
Sort comments with instant comparison and stable tie-breaking
Two subtle bugs trip up naive comment sorting:
- Comparing timestamp strings alphabetically instead of as points in time. In ISO 8601 (the standard
"YYYY-MM-DDTHH:MM:SSZ"date format),"2025-01-01T10:00:00+02:00"equals08:00 UTC, which happened before"2025-01-01T09:00:00Z"(09:00 UTC). Alphabetically"10:00"comes after"09:00", giving the wrong order! Converting every timestamp to Unix epoch seconds (seconds elapsed since1970-01-01T00:00:00Z) compares exact instants. - Flipping tie-break order when reversing. Several comments often share the same
userId, and two comments can share the same timestamp. Ties must always resolve older timestamp first, then smalleridin both ascending and descending modes so tied rows never jump around.
If you sort ascending and reverse the final list (
result[::-1]), ties flip upside down too. Instead, use a two-pass stable sort (a stable sort guarantees that two items with equal sort keys keep their previous relative order):Input comments: id=20(user=100, 14:06), id=50(user=100, 14:03), id=60(user=300, 13:45) Pass 1 — sort by tie-breaker (timestamp asc, id asc): id=60(user=300, 13:45), id=50(user=100, 14:03), id=20(user=100, 14:06) [50 precedes 20 because 14:03 < 14:06] Pass 2 — stable sort by userId with reverse=True ("desc"): id=60(user=300, 13:45), id=50(user=100, 14:03), id=20(user=100, 14:06) [user 300 comes before user 100, and 50 stays before 20!]Python's built-in Timsort preserves stability even when
reverse=True, so two clean passes handle both directions without custom comparator classes:def parse_timestamp(value: Any) -> float: """Seconds since the epoch for an ISO 8601 string; a number is used as is. A string without a UTC offset is read as UTC.""" if isinstance(value, (int, float)): return float(value) # Python < 3.11 needs "+00:00" instead of trailing "Z" in fromisoformat. iso_text = value.replace("Z", "+00:00") moment = datetime.fromisoformat(iso_text) # Treat timezone-naive strings as UTC so every string maps to a well-defined instant. if moment.tzinfo is None: moment = moment.replace(tzinfo=timezone.utc) return moment.timestamp() def check_sort(field: str, direction: str) -> None: """Validate field and direction up front before sorting or writing to storage.""" if field not in SORT_FIELDS: raise ValueError(f"cannot sort by {field!r}") if direction not in SORT_DIRECTIONS: raise ValueError(f"unknown direction {direction!r}") def _time_key(comment: Comment) -> float: return parse_timestamp(comment["timestamp"]) def _user_key(comment: Comment) -> Any: return comment["userId"] def _tie_break_key(comment: Comment) -> Tuple[float, Any]: # Ties always resolve older timestamp first, then smaller id. return (parse_timestamp(comment["timestamp"]), comment["id"]) def sort_comments(comments: List[Comment], field: str = "timestamp", direction: str = "desc") -> List[Comment]: """A new list sorted by field in the given direction. Ties are always ordered older first, then by smaller id, in both directions.""" check_sort(field, direction) # Pass 1: create a fresh list ordered by the tie-breaker (older first, then smaller id). ordered = sorted(comments, key=_tie_break_key) # Pass 2: Python's Timsort is stable even when reverse=True, so items with equal # primary keys keep their Pass 1 tie-break order instead of flipping backwards. is_descending = direction == "desc" if field == "timestamp": ordered.sort(key=_time_key, reverse=is_descending) else: ordered.sort(key=_user_key, reverse=is_descending) return ordered- Comparing timestamp strings alphabetically instead of as points in time. In ISO 8601 (the standard
Persist the sort choice safely in string storage
In-memory component state resets whenever the user reloads the browser tab. Because the server is unchanged, we persist the sort setting in browser
localStorage(persistent per-origin string storage that survives reloads and browser restarts).Two rules keep persistence bug-free: - Serialize to a JSON string on write:
localStorageonly accepts strings. Saving a raw JavaScript object converts it into the useless text"[object Object]", so serialize{"field": field, "direction": direction}withjson.dumps. - Validate every step on read: Storage might be empty on a first visit, contain broken JSON edited in DevTools, store a JSON list instead of an object, or name a deprecated field removed in a newer release. Any invalid state should fall back gracefully toDEFAULT_SORT = ("timestamp", "desc")instead of crashing the UI.def save_sort_preference(storage: MutableMapping[str, str], field: str, direction: str) -> None: """Write the choice as a JSON string, the only value type localStorage can hold.""" check_sort(field, direction) # Browser localStorage maps string keys to string values, so serialize as JSON text. payload = {"field": field, "direction": direction} storage[STORAGE_KEY] = json.dumps(payload) def load_sort_preference(storage: MutableMapping[str, str]) -> Tuple[str, str]: """The saved (field, direction), or DEFAULT_SORT if nothing valid is stored.""" raw_value = storage.get(STORAGE_KEY) if raw_value is None: return DEFAULT_SORT # Guard against corrupted strings or manual edits in browser storage. try: saved = json.loads(raw_value) except (TypeError, ValueError): return DEFAULT_SORT if not isinstance(saved, dict): return DEFAULT_SORT field = saved.get("field") direction = saved.get("direction") if field not in SORT_FIELDS or direction not in SORT_DIRECTIONS: return DEFAULT_SORT return field, directionBuild the nested comment tree in one linear pass
A naive tree builder loops over every comment and scans the entire list looking for its children, taking
O(n^2)work (100,000,000checks for10,000comments). We can build the entire nested tree in one dictionary pass after sorting:- Create a lookup dictionary
nodesmapping eachcomment["id"]to a fresh copy of that comment with"children": []. - Iterate through
sort_comments(comments, field, direction)in order. For each comment, look up its parent innodesinO(1)time and appendnodetonodes[parent_id]["children"](or torootsif it has no valid parent innodes).
Because we visit comments in the exact target sort order,
rootsand every"children"list receive siblings in sorted order automatically—no recursive per-node sorting needed!nodes lookup table: 10 -> {"id": 10, ..., "children": []} 20 -> {"id": 20, "parentId": 10, ..., "children": []} 50 -> {"id": 50, "parentId": 10, ..., "children": []} Visit in "timestamp desc" order: [20 (14:06), 50 (14:03), 10 (14:00)] - visit 20: parent 10 is in nodes -> nodes[10]["children"].append(node 20) - visit 50: parent 10 is in nodes -> nodes[10]["children"].append(node 50) - visit 10: parent is None -> roots.append(node 10) Result: roots = [10], and node 10's children = [20, 50] (newest reply first!)Notice that
node 20safely attaches tonodes[10]["children"]beforenode 10itself is appended toroots, because every node dictionary already exists innodesfrom Phase 1. Also, any orphan node (a comment whoseparentIdis missing because the parent was deleted or excluded by filtering) or buggy self-reference (parentId == id) safely becomes a root instead of vanishing:def build_tree(comments: List[Comment], field: str = "timestamp", direction: str = "desc") -> List[Dict[str, Any]]: """Nest comments by parentId. Each node is a copy of the comment plus a "children" list. Roots and every children list are in sort order. A comment whose parent is missing (or is itself) becomes a root instead of being dropped.""" # Phase 1: copy each comment into nodes: {comment_id: {..., "children": []}} # Copying avoids mutating the caller's mock data across repeated renders. nodes: Dict[Any, Dict[str, Any]] = {} for comment in comments: node = dict(comment) node["children"] = [] nodes[comment["id"]] = node # Phase 2: walk comments in final sort order so every parent's "children" list # and the top-level "roots" list are populated in sorted order automatically. roots: List[Dict[str, Any]] = [] sorted_comments = sort_comments(comments, field, direction) for comment in sorted_comments: comment_id = comment["id"] node = nodes[comment_id] parent_id = comment["parentId"] # Promote top-level comments, self-parenting bugs, and orphans (including replies # whose parent was hidden by filter_comments) to top-level roots. if parent_id is None or parent_id == comment_id or parent_id not in nodes: roots.append(node) else: nodes[parent_id]["children"].append(node) return roots- Create a lookup dictionary
Filter matching comments and all their descendants
Text filtering must retain every comment whose
contentcontains the query plus all of its descendants (replies, replies-to-replies, and so on), hiding everything else.Walking downward from matching comments is a textbook depth-first search (DFS) (exploring a tree or graph by pushing items onto a stack and visiting all reachable children):
- Build an adjacency list
children_by_parent(a dictionary mapping eachparent_idto a list of directchild_ids). - Push every comment ID whose
contentcontains the search text (using.casefold()for thorough case-insensitive matching) ontostack. - Pop an ID from
stack, skip it if it is already invisible_ids, otherwise add it tovisible_idsand push all of its direct children ontostack.
Thread structure: 10 ("Index reduced...") -> 20 ("Watch write amplification...") -> 30 ("Good catch...") Query: "AMPLIFICATION" 1. Seed stack with text matches: stack = [20], visible_ids = {} 2. Pop 20 -> add 20 to visible_ids; push children of 20 -> stack = [30] 3. Pop 30 -> add 30 to visible_ids; push children of 30 -> stack = [] 4. Keep input comments in visible_ids: [comment 20, comment 30] (Comment 10 did not match, so it stays hidden.)The
visible_idsset serves double duty: if both a parent and its reply contain"index", we never traverse the reply's subtree twice, and if corrupt data ever had a cycle, the loop still terminates inO(n)steps:def filter_comments(comments: List[Comment], query: str) -> List[Comment]: """The comments whose content contains query (case-insensitive) plus all of their descendants, in input order. A blank query keeps every comment.""" # Strip surrounding whitespace and casefold for full Unicode case-insensitive matching. needle = query.strip().casefold() if not needle: return list(comments) # Phase 1: build adjacency list children_by_parent: {parent_id: [child_id, ...]} children_by_parent: Dict[Any, List[Any]] = {} for comment in comments: parent_id = comment["parentId"] if parent_id is not None: if parent_id not in children_by_parent: children_by_parent[parent_id] = [] children_by_parent[parent_id].append(comment["id"]) # Phase 2: seed the DFS stack with every comment whose own text matches the query. stack: List[Any] = [] for comment in comments: if needle in comment["content"].casefold(): stack.append(comment["id"]) # Phase 3: walk downward so every reply, grand-reply, etc. of a match is marked visible. # Checking visible_ids skips duplicate work and stops infinite loops if data has a cycle. visible_ids = set() while stack: comment_id = stack.pop() if comment_id in visible_ids: continue visible_ids.add(comment_id) for child_id in children_by_parent.get(comment_id, []): stack.append(child_id) # Phase 4: collect visible comments while preserving the original input order. visible_comments: List[Comment] = [] for comment in comments: if comment["id"] in visible_ids: visible_comments.append(comment) return visible_comments- Build an adjacency list
Connect everything inside CommentView
CommentViewwraps the exact state a frontend component manages: - On construction (initial load or page reload), it loads(self.field, self.direction)fromstorageand starts with an emptyself.query. -set_sortcallssave_sort_preferencefirst so an invalid field or direction raisesValueErrorbefore mutatingself.fieldorself.direction. -set_filterupdatesself.queryin memory only (search text is transient, whereas sort preference persists). -visible_treechainsfilter_commentsintobuild_tree.class CommentView: """State behind the comment UI. The sort choice is persisted in storage (localStorage in the browser), so a new CommentView on the same storage, like a page refresh, restores it. The filter text is not persisted.""" def __init__(self, comments: List[Comment], storage: MutableMapping[str, str]): # Shallow-copy the list so external list edits cannot surprise the view. self.comments = list(comments) self.storage = storage self.field, self.direction = load_sort_preference(storage) self.query = "" def set_sort(self, field: str, direction: str) -> None: # Validate and save to storage first so an invalid choice leaves self.field untouched. save_sort_preference(self.storage, field, direction) self.field = field self.direction = direction def set_filter(self, query: str) -> None: self.query = query def visible_tree(self) -> List[Dict[str, Any]]: # Filter the flat list first; build_tree then promotes any orphaned match to a root. shown_comments = filter_comments(self.comments, self.query) return build_tree(shown_comments, self.field, self.direction)In a client-rendered React app, those exact helpers power a small recursive
<CommentNode />component (note: in server-side rendered apps like Next.js, readwindow.localStorageinsideuseEffectafter mount becausewindowis undefined on the server):function CommentSection({ comments }) { const [sort, setSort] = useState(() => loadSortPreference(window.localStorage)); const [query, setQuery] = useState(""); useEffect(() => { try { saveSortPreference(window.localStorage, sort.field, sort.direction); } catch { // Ignore storage quota or privacy-mode errors; in-memory state still works. } }, [sort]); const tree = useMemo( () => buildTree(filterComments(comments, query), sort.field, sort.direction), [comments, query, sort] ); return <ul>{tree.map((node) => <CommentNode key={node.id} node={node} />)}</ul>; } function CommentNode({ node }) { return ( <li> <p>{node.content}</p> {node.children.length > 0 && ( <ul>{node.children.map((child) => <CommentNode key={child.id} node={child} />)}</ul> )} </li> ); }Walk through Examples 1 and 2 on the 6-comment dataset
Let us trace all six sample comments across sorting, refreshing, and filtering:
id userId time (UTC) parentId content --- ------ ---------- -------- --------------------------------------- 10 200 14:00 None "Index reduced query latency" 20 100 14:06 10 "Watch write amplification on inserts" 30 300 14:12 20 "Good catch, benchmarked bulk loads" 40 200 13:15 None "Deploy window moved to Friday" 50 100 14:03 10 "Composite index helped dashboard too" 60 300 13:45 40 "Acknowledged by on-call"- Default load (
timestamp,"desc"): Roots10(14:00) and40(13:15) appear newest-first. Under10, reply20(14:06) appears above reply50(14:03):text 10 "Index reduced query latency" (user 200, 14:00) |-- 20 "Watch write amplification on inserts" (user 100, 14:06) | `-- 30 "Good catch, benchmarked bulk loads" (user 300, 14:12) `-- 50 "Composite index helped dashboard too" (user 100, 14:03) 40 "Deploy window moved to Friday" (user 200, 13:15) `-- 60 "Acknowledged by on-call" (user 300, 13:45) - Select
("userId", "asc")and reload (Example 1):storage["comments.sort"]holds'{"field": "userId", "direction": "asc"}'. A freshCommentViewrestores("userId", "asc"). Roots40and10both belong touserId = 200, so the tie-breaker puts older40(13:15) before10(14:00); under10, replies50(14:03) and20(14:06) both belong touserId = 100, so50appears before20. - Filter
"AMPLIFICATION"(Example 2): Only comment20matches by text; DFS marks20and its child30visible ([20, 30]). Inbuild_tree,20'sparentId(10) is not innodes, so20lifts cleanly to a root with child30nested underneath, while thread40 -> 60disappears completely.
- Default load (
Complete solution
from typing import Any, Dict, List, MutableMapping, Tuple import json from datetime import datetime, timezone # Each raw comment dictionary has shape: # {"id": 10, "userId": 200, "timestamp": "2025-03-15T14:00:00Z", "content": "...", "parentId": None} Comment = Dict[str, Any] SORT_FIELDS = ("timestamp", "userId") SORT_DIRECTIONS = ("asc", "desc") DEFAULT_SORT = ("timestamp", "desc") # newest first when nothing valid is saved STORAGE_KEY = "comments.sort" def parse_timestamp(value: Any) -> float: """Seconds since the epoch for an ISO 8601 string; a number is used as is. A string without a UTC offset is read as UTC.""" if isinstance(value, (int, float)): return float(value) # Python < 3.11 needs "+00:00" instead of trailing "Z" in fromisoformat. iso_text = value.replace("Z", "+00:00") moment = datetime.fromisoformat(iso_text) # Treat timezone-naive strings as UTC so every string maps to a well-defined instant. if moment.tzinfo is None: moment = moment.replace(tzinfo=timezone.utc) return moment.timestamp() def check_sort(field: str, direction: str) -> None: """Validate field and direction up front before sorting or writing to storage.""" if field not in SORT_FIELDS: raise ValueError(f"cannot sort by {field!r}") if direction not in SORT_DIRECTIONS: raise ValueError(f"unknown direction {direction!r}") def _time_key(comment: Comment) -> float: return parse_timestamp(comment["timestamp"]) def _user_key(comment: Comment) -> Any: return comment["userId"] def _tie_break_key(comment: Comment) -> Tuple[float, Any]: # Ties always resolve older timestamp first, then smaller id. return (parse_timestamp(comment["timestamp"]), comment["id"]) def sort_comments(comments: List[Comment], field: str = "timestamp", direction: str = "desc") -> List[Comment]: """A new list sorted by field in the given direction. Ties are always ordered older first, then by smaller id, in both directions.""" check_sort(field, direction) # Pass 1: create a fresh list ordered by the tie-breaker (older first, then smaller id). ordered = sorted(comments, key=_tie_break_key) # Pass 2: Python's Timsort is stable even when reverse=True, so items with equal # primary keys keep their Pass 1 tie-break order instead of flipping backwards. is_descending = direction == "desc" if field == "timestamp": ordered.sort(key=_time_key, reverse=is_descending) else: ordered.sort(key=_user_key, reverse=is_descending) return ordered def save_sort_preference(storage: MutableMapping[str, str], field: str, direction: str) -> None: """Write the choice as a JSON string, the only value type localStorage can hold.""" check_sort(field, direction) # Browser localStorage maps string keys to string values, so serialize as JSON text. payload = {"field": field, "direction": direction} storage[STORAGE_KEY] = json.dumps(payload) def load_sort_preference(storage: MutableMapping[str, str]) -> Tuple[str, str]: """The saved (field, direction), or DEFAULT_SORT if nothing valid is stored.""" raw_value = storage.get(STORAGE_KEY) if raw_value is None: return DEFAULT_SORT # Guard against corrupted strings or manual edits in browser storage. try: saved = json.loads(raw_value) except (TypeError, ValueError): return DEFAULT_SORT if not isinstance(saved, dict): return DEFAULT_SORT field = saved.get("field") direction = saved.get("direction") if field not in SORT_FIELDS or direction not in SORT_DIRECTIONS: return DEFAULT_SORT return field, direction def build_tree(comments: List[Comment], field: str = "timestamp", direction: str = "desc") -> List[Dict[str, Any]]: """Nest comments by parentId. Each node is a copy of the comment plus a "children" list. Roots and every children list are in sort order. A comment whose parent is missing (or is itself) becomes a root instead of being dropped.""" # Phase 1: copy each comment into nodes: {comment_id: {..., "children": []}} # Copying avoids mutating the caller's mock data across repeated renders. nodes: Dict[Any, Dict[str, Any]] = {} for comment in comments: node = dict(comment) node["children"] = [] nodes[comment["id"]] = node # Phase 2: walk comments in final sort order so every parent's "children" list # and the top-level "roots" list are populated in sorted order automatically. roots: List[Dict[str, Any]] = [] sorted_comments = sort_comments(comments, field, direction) for comment in sorted_comments: comment_id = comment["id"] node = nodes[comment_id] parent_id = comment["parentId"] # Promote top-level comments, self-parenting bugs, and orphans (including replies # whose parent was hidden by filter_comments) to top-level roots. if parent_id is None or parent_id == comment_id or parent_id not in nodes: roots.append(node) else: nodes[parent_id]["children"].append(node) return roots def filter_comments(comments: List[Comment], query: str) -> List[Comment]: """The comments whose content contains query (case-insensitive) plus all of their descendants, in input order. A blank query keeps every comment.""" # Strip surrounding whitespace and casefold for full Unicode case-insensitive matching. needle = query.strip().casefold() if not needle: return list(comments) # Phase 1: build adjacency list children_by_parent: {parent_id: [child_id, ...]} children_by_parent: Dict[Any, List[Any]] = {} for comment in comments: parent_id = comment["parentId"] if parent_id is not None: if parent_id not in children_by_parent: children_by_parent[parent_id] = [] children_by_parent[parent_id].append(comment["id"]) # Phase 2: seed the DFS stack with every comment whose own text matches the query. stack: List[Any] = [] for comment in comments: if needle in comment["content"].casefold(): stack.append(comment["id"]) # Phase 3: walk downward so every reply, grand-reply, etc. of a match is marked visible. # Checking visible_ids skips duplicate work and stops infinite loops if data has a cycle. visible_ids = set() while stack: comment_id = stack.pop() if comment_id in visible_ids: continue visible_ids.add(comment_id) for child_id in children_by_parent.get(comment_id, []): stack.append(child_id) # Phase 4: collect visible comments while preserving the original input order. visible_comments: List[Comment] = [] for comment in comments: if comment["id"] in visible_ids: visible_comments.append(comment) return visible_comments class CommentView: """State behind the comment UI. The sort choice is persisted in storage (localStorage in the browser), so a new CommentView on the same storage, like a page refresh, restores it. The filter text is not persisted.""" def __init__(self, comments: List[Comment], storage: MutableMapping[str, str]): # Shallow-copy the list so external list edits cannot surprise the view. self.comments = list(comments) self.storage = storage self.field, self.direction = load_sort_preference(storage) self.query = "" def set_sort(self, field: str, direction: str) -> None: # Validate and save to storage first so an invalid choice leaves self.field untouched. save_sort_preference(self.storage, field, direction) self.field = field self.direction = direction def set_filter(self, query: str) -> None: self.query = query def visible_tree(self) -> List[Dict[str, Any]]: # Filter the flat list first; build_tree then promotes any orphaned match to a root. shown_comments = filter_comments(self.comments, self.query) return build_tree(shown_comments, self.field, self.direction)✅ Submit now — all tests should pass.
Intuition & how it works
Imagine organizing a box of loose sticky notes where each reply note only writes down the ID number of the note it replied to (parentId). Instead of rummaging through the whole box over and over to find replies for each note, you first lay every note on a numbered table (nodes dictionary), toss out branches that do not match the user's search filter, sort the remaining notes once, and clip each note under its parent in a single pass. Saving the user's chosen sort setting as a small JSON string in localStorage (the browser's persistent string key-value store) ensures a page reload restores the exact same ordering.
The naive approach fails on three fronts: scanning the full comment list inside a loop to find each parent's children takes O(n^2) work, comparing raw ISO 8601 date strings (such as "2025-01-01T10:00:00+02:00" vs "2025-01-01T09:00:00Z") alphabetically puts earlier timezone-offset moments in the wrong place, and filtering after building the tree accidentally drops matching replies whenever their top-level parent does not contain the search word.
Walk through four comments from the sample dataset to see why filtering the flat list before building the tree is so clean:
- Suppose we have root 10 (14:00, "Index reduced query latency"), reply 20 (14:06, parentId=10, "Watch write amplification on inserts"), grand-reply 30 (14:12, parentId=20, "Good catch, benchmarked bulk loads"), and root 40 (13:15, "Deploy window moved to Friday").
- With no filter and default ("timestamp", "desc") sort, build_tree walks comments newest-first (30, 20, 10, 40), attaching 30 under 20, 20 under 10, and placing root 10 above root 40.
- Now the user filters by "AMPLIFICATION". filter_comments seeds a stack with matching ID 20, walks down its children to mark {20, 30} visible, and excludes 10 and 40.
- Next, build_tree receives [20, 30], sees that 20's parentId (10) is absent from the visible dictionary, and automatically promotes 20 (with child 30 still nested under it) to a top-level root.
Complexity
Let n be the number of comments, L be the total number of characters across all comment content strings, and q be the length of the filter query:
sort_comments—O(n log n)time,O(n)space: We run two passes of Python's stable sort (a sort that preserves the prior order of items with equal keys), computing a timestamp or user key once per comment (O(n)key evaluations andO(n log n)comparisons) and returning a newn-element list.build_tree—O(n log n)time,O(n)space: Creating thenodesdictionary copies allncomments once (O(n)), sorting takesO(n log n), and linking each node to its parent does oneO(1)dictionary lookup per comment (O(n)). Thenodesmap and"children"lists holdnnode dictionaries total.filter_comments—O(n + L * q)time,O(n)space: Building the adjacency list (a map from eachparent_idto its list ofchild_ids) scansncomments once, substring matching checksLtotal characters against aq-character needle (O(L * q)worst case, typically nearO(L)), and the depth-first search (DFS) (stack-based downward traversal) visits each comment ID at most once thanks tovisible_ids. The map, stack, and set store at mostnIDs.save_sort_preference/load_sort_preference—O(1)time and space: Both serialize or parse one tiny two-field JSON string ({"field": ..., "direction": ...}).CommentView.visible_tree—O(n log n + L * q)time,O(n)space: Runsfilter_commentsfollowed bybuild_treeon the visible subset.
Edge cases
- Empty comment list or zero filter matches: Both
filter_commentsandbuild_treereturn[]cleanly without crashing. - Blank or whitespace-only filter (
""or" "):query.strip()becomes empty, returning a shallow copy of all comments so typing a stray space does not blank out the page. - Matching reply under a non-matching parent: Filtering first removes the parent, and
build_treepromotes the matching orphan node (a node whoseparentIdis absent from the active dataset) to a root along with all of its descendants. - Nested matches (parent and reply both match the query): The
visible_idsset skips any ID already visited, so no comment is duplicated or traversed twice. - Deleted parent (
parentId = 999) or self-parenting bug (parentId == id):build_treechecksparent_id == comment_id or parent_id not in nodesand renders them safely at the root level instead of dropping them or creating an infinite self-child loop. - Multi-node parent cycle (
A -> B -> A):filter_commentsterminates safely becausevisible_idsstops cycles, andbuild_treefinishes in one non-recursive pass (cyclic nodes have no root, so they stay detached fromroots). - Ties on
userIdortimestamp: Always broken older-first (parse_timestamp), then by smallerid, in both"asc"and"desc"modes so rows never swap places unpredictably. - Mixed timezone offsets and naive timestamps: Converting through
parse_timestampinto Unix epoch seconds (seconds since1970-01-01T00:00:00Z) compares true instants; strings without an explicit offset default consistently to UTC. - Missing, corrupted, or outdated storage payloads:
load_sort_preferencecatches missing keys, invalid JSON, non-dict JSON values (such as["userId", "asc"]), and unknown fields/directions, returningDEFAULT_SORT.
Common mistakes
- Sorting only root comments and leaving reply lists unsorted: Replies then appear in arbitrary arrival order; iterating through
sort_comments(...)while attaching children sorts every depth level automatically. - Building the tree with nested array scans (
comments.filter(c => c.parentId === node.id)): Turns a fastO(n)dictionary pass into anO(n^2)bottleneck on large threads. - Mutating the original comment dictionaries in place: Adding
comment["children"] = []directly onto the input objects causes duplicate children to pile up on subsequent renders and breaks React state immutability. - Implementing
"desc"by reversing the"asc"list (asc_list[::-1]): Reversing at the end flips tie-breakers backwards too (putting newer comments or larger IDs first among equaluserIds). - Comparing raw timestamp strings: Fails whenever offsets differ (
"+02:00"vs"Z"). - Storing a raw object in
localStoragewithout JSON serialization, or accessingwindow.localStorageunconditionally during server-side rendering (SSR) wherewindowis undefined.
Alternative approaches
- Build the full tree first, then prune recursively for filtering: A recursive helper returns the entire subtree as-is when a node matches, or collects any surviving subtrees returned by its children when the node itself does not match. Time complexity is the same
O(n log n + L * q), but you have to write explicit subtree-lifting logic that flat-list filtering gets for free frombuild_tree's orphan rule. - Persist sort state in URL query parameters (
?sort=userId&dir=asc): Survives page refreshes AND lets users share a link that opens in the same sort order, though opening a brand-new link without query parameters reverts to defaults. Production UIs often check URL parameters first and fall back tolocalStorage.
Follow-up questions
- How would you modify filtering so the ancestor chain above a matching reply also appears as dimmed context? Keep the downward pass for full matching subtrees, then add a brief upward pass from each direct text match along
parentIdpointers until hittingNoneor an already-marked node, tagging visited ancestors with"isContext": True. Because each node's parent pointer is traversed at most once when guarded by avisitedset, the extra pass adds onlyO(n)time andO(n)space while giving readers full thread context. - How would you keep rendering and search responsive when a thread grows to 50,000 comments? The
O(n log n)data pipeline runs in tens of milliseconds, so creating 50,000 DOM elements is the real bottleneck. Flatten the visible tree via pre-order traversal into a single array of(comment, depth)rows and apply list virtualization (rendering only the ~30 rows currently inside the scroll viewport, indented bydepth * 16px), pair the search box with debouncing (waiting ~200 ms after the user stops typing before recomputing), and precomputecontent.casefold()once on load. - If the same discussion page is open in two browser tabs, how can changing the sort order in one tab synchronize the other? Browsers automatically dispatch a
window"storage"event in every other open tab of the same origin wheneverlocalStorage.setItemmodifies a key. Attaching awindow.addEventListener("storage", ...)listener that checksevent.key === STORAGE_KEY, runs the same defensiveloadSortPreferencevalidator, and updates component state keeps all open tabs synchronized safely.
Follow-up questions
- How would you modify filtering so the ancestor chain above a matching reply also appears as dimmed context?
- How would you keep rendering and search responsive when a thread grows to 50,000 comments?
- If the same discussion page is open in two browser tabs, how can changing the sort order in one tab synchronize the other?
Similar questions
- Construct Comment Hierarchy from Flat Replies
- Browser-Only Threaded Comment Widget with Local Persistence
- Sortable Comments and Async Image Service
- Diagnosing Frontend Latency and Managing Production Incidents
- 2D Max Pooling with Source Coordinates
- Time-Limited Credit Ledger