Threaded Comment Feed: Filtering, Nesting, and Persistent Sort
Trees & GraphsModel answerLast updated
Transform a flat array of comments into a sorted, nested, filterable tree while persisting the user's sort preference across sessions.
Threaded Comment Feed
You are building the client-side logic for a comment section. The backend hands you a flat array of comment objects. Your job is to turn that raw data into a sorted, nested, filterable structure — without touching the backend.
Each comment object has these fields:
| Field | Type | Description |
|---|---|---|
id | string | Unique identifier |
userId | string | ID of the author |
timestamp | string or number | ISO 8601 string or epoch ms |
content | string | Body text of the comment |
parentId | string or null | ID of the parent comment, or null for top-level |
Implement the following behaviors:
1. Nested display
Reconstruct the thread hierarchy from parentId references alone. A comment whose parentId is null, or whose parent does not exist in the data, should be treated as a top-level comment. Do not modify the flat input array.
2. Sortable list
Allow the user to sort comments by either timestamp or userId, in ascending or descending order. Sorting must apply at every level of nesting — siblings are sorted among themselves, not globally across the whole flat list.
3. Persistent sort preference
When the user picks a sort field or direction, save that choice so it survives a page refresh. On load, restore the saved preference; if it is missing, invalid, or unreadable, fall back to timestamp ascending.
4. Content filter
Provide a text input that filters comments by their content field (case-insensitive substring match). The rule for what to show: if a comment matches the query, show it and every one of its descendants, even if the descendants do not themselves match. If a comment does not match and none of its descendants match, hide it entirely. Non-matching ancestors are not shown.
Assumptions
- Treat the data as local mock data; no network calls are needed.
- The filter string is transient — do not persist it.
- Cycles or self-references in
parentIdare possible; handle them without crashing.
What to produce Write the core logic functions and explain your approach. Include time and space complexity, and describe the edge cases your solution handles.
Hints
Hint 1
Think of the work as a pipeline with three independent stages: build the tree once, then filter it, then sort it. Each stage should be a pure function that returns new objects rather than mutating the input.
Hint 2
For the filter, a pre-order DFS works well. When you reach a node that matches, you can stop descending — its entire subtree is already included. When a node doesn't match, keep searching its children anyway, because a reply deeper down might match.
Hint 3
localStorage can hold stale or corrupted data. Always validate the loaded value against your list of allowed fields and directions before using it, and fall back to your defaults if anything looks wrong.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The key insight is to keep the three concerns — tree construction, filtering, and sorting — as separate pure functions operating in sequence:
flat array → build() → forest → filter() → forest → sort() → render
↑
localStorage: { field, direction }
Memoize build() since the raw data never changes when the user adjusts the sort or filter.
Stage 1: Build the tree
Create a map from id to a new node object (with an empty children array). Walk every node: if its parentId maps to an existing node, attach it there; otherwise make it a root. This is O(n).
The one subtlety is cycles — parentId chains that loop back on themselves. Detect them with a path-coloring pass before attaching nodes: if following parentId links from a given node eventually returns to a node already on the current path, sever that edge and treat the cycle-closing node as a root.
Stage 2: Filter
Run a pre-order iterative DFS (iterative avoids stack overflow on deep threads). For each node:
- If
contentmatches the query → emit the node with its entire subtree intact; do not recurse into children. - If it does not match → skip the node itself but push its children onto the stack to keep searching.
This satisfies the spec exactly: matching nodes surface with all descendants, non-matching nodes with no matching descendants are invisible, and a matching reply appears even if its ancestor does not match (it becomes a root in the filtered result).
Empty or whitespace-only query → return the full tree unchanged.
Stage 3: Sort
Sort the children array at every node recursively, using the chosen field as the primary key and id as a deterministic tie-breaker. Sorting a flat list would silently break the parent-child relationships, which is a common mistake here. Both ISO timestamp strings and epoch numbers need to be normalized to a common numeric form before comparing.
Persistence
Save { field, direction } as a JSON string under a single localStorage key. On load, parse it, check that both values are in the allowed sets, and fall back to { field: "timestamp", direction: "asc" } if anything is wrong. This guards against stale formats, manual edits, or storage being cleared mid-session.
Complexity
| Stage | Time | Space |
|---|---|---|
| Build | O(n) | O(n) |
| Filter | O(n · L) where L = avg content length | O(n) |
| Sort | O(n log n) across all sibling groups | O(n) call stack avoided by iterative DFS |
Python implementation
storage is a dict standing in for localStorage.
import json
from datetime import datetime
SORT_FIELDS = ("timestamp", "userId")
DIRECTIONS = ("asc", "desc")
DEFAULTS = {"field": "timestamp", "direction": "asc"}
STORAGE_KEY = "commentFeed.sortPrefs"
# ── persistence ───────────────────────────────────────────────
def load_prefs(storage: dict) -> dict:
try:
prefs = json.loads(storage.get(STORAGE_KEY) or "{}")
if not isinstance(prefs, dict):
prefs = {}
except (TypeError, ValueError):
prefs = {}
field = prefs.get("field")
direction = prefs.get("direction")
return {
"field": field if field in SORT_FIELDS else DEFAULTS["field"],
"direction": direction if direction in DIRECTIONS else DEFAULTS["direction"],
}
def save_prefs(storage: dict, field: str, direction: str) -> None:
if field not in SORT_FIELDS or direction not in DIRECTIONS:
raise ValueError(f"Invalid prefs: {field!r}, {direction!r}")
storage[STORAGE_KEY] = json.dumps({"field": field, "direction": direction})
# ── tree construction ─────────────────────────────────────────
def _parent_map(by_id: dict) -> dict:
"""Resolve parentId for every node, severing any cycle-closing edge."""
parent_of = {
cid: (c.get("parentId") if c.get("parentId") in by_id else None)
for cid, c in by_id.items()
}
resolved: set = set()
for start in by_id:
path, seen, cur = [], set(), start
while cur is not None and cur not in resolved and cur not in seen:
seen.add(cur)
path.append(cur)
cur = parent_of[cur]
if cur is not None and cur in seen: # cycle detected
parent_of[cur] = None # sever edge → cur becomes a root
resolved.update(path)
return parent_of
def build_tree(comments: list) -> list:
"""Return a forest of node dicts (each with a 'children' list)."""
by_id = {c["id"]: c for c in comments}
parent = _parent_map(by_id)
nodes = {cid: {**c, "children": []} for cid, c in by_id.items()}
roots: list = []
for cid, node in nodes.items():
pid = parent[cid]
target = nodes[pid]["children"] if pid is not None else roots
target.append(node)
return roots
# ── filter ────────────────────────────────────────────────────
def filter_tree(roots: list, query: str) -> list:
q = (query or "").strip().casefold()
if not q:
return roots
result: list = []
stack = list(reversed(roots))
while stack:
node = stack.pop()
if q in str(node.get("content", "")).casefold():
result.append(node) # keep full subtree
else:
stack.extend(reversed(node["children"])) # keep searching children
return result
# ── sort ──────────────────────────────────────────────────────
def _to_epoch(ts) -> float:
if isinstance(ts, (int, float)):
return float(ts)
return datetime.fromisoformat(str(ts).replace("Z", "+00:00")).timestamp()
def sort_tree(roots: list, field: str, direction: str) -> list:
if field not in SORT_FIELDS or direction not in DIRECTIONS:
raise ValueError("Invalid sort option")
reverse = direction == "desc"
def sort_key(node):
raw = node.get(field, "")
val = _to_epoch(raw) if field == "timestamp" else str(raw)
return (val, node["id"])
def sort_nodes(nodes: list) -> list:
sorted_nodes = sorted(nodes, key=sort_key, reverse=reverse)
for node in sorted_nodes:
node["children"] = sort_nodes(node["children"])
return sorted_nodes
return sort_nodes(roots)
# ── pipeline ──────────────────────────────────────────────────
def render_pipeline(comments: list, query: str, storage: dict) -> list:
prefs = load_prefs(storage)
forest = build_tree(comments)
forest = filter_tree(forest, query)
forest = sort_tree(forest, prefs["field"], prefs["direction"])
return forest
Edge cases worth calling out
- Orphan comments (
parentIdpoints to a non-existent ID): become roots, no data is lost. - Cycles (
A → B → A): the cycle-breaking pass severs exactly one edge so every node still appears once. - Mixed timestamp formats:
_to_epochhandles both ISO strings (with or withoutZ) and numeric epochs. - Empty filter: returning the full tree unchanged avoids unnecessary traversal work.
- Stale localStorage: validated on every load; bad data is silently replaced with defaults rather than throwing.
- Timestamp ties: secondary sort on
idmakes ordering stable and reproducible across browsers.
Common mistakes
- Sorting the flat array instead of sibling groups — destroys the nesting.
- Filtering by hiding nodes in the DOM instead of pruning the data structure — descendants of non-matching ancestors still appear.
- Mutating the original comment objects — causes subtle bugs when re-running the pipeline after a sort change.
- Skipping validation on
localStoragereads — a stored value from an older version of the app can break the sort silently.