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 comment
  • userId: identifier of the author who posted it
  • timestamp: 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 (int or float). A helper parse_timestamp(value) is already provided.
  • content: body text of the comment
  • parentId: id of the comment it replies to, or None for a top-level post

Implement the client-side data helpers and stateful controller defined in starter.py:

  1. sort_comments(comments, field="timestamp", direction="desc") — Return a new list ordered by field ("timestamp" comparing parsed instants, or "userId") in direction ("asc" or "desc"), without mutating comments. Raise ValueError for any other field or direction. Whenever two comments tie on the primary sort key, order the older timestamp first and then the smaller id first in both "asc" and "desc" modes.
  2. save_sort_preference(storage, field, direction) & load_sort_preference(storage) — Persist and restore the user's sort setting in storage (a MutableMapping[str, str] modeling browser localStorage, where keys and values are strings) under STORAGE_KEY = "comments.sort". save_sort_preference raises ValueError on invalid choices; load_sort_preference returns DEFAULT_SORT = ("timestamp", "desc") whenever nothing is stored or the stored string is malformed or unsupported.
  3. build_tree(comments, field="timestamp", direction="desc") — Assemble a nested forest from flat parentId links 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 follow sort_comments order. Any comment whose parentId is None, equals its own id, or does not match any comment in comments is placed at the root level.
  4. filter_comments(comments, query) — Trim surrounding whitespace from query; if blank, return a shallow copy of comments. Otherwise match query case-insensitively as a substring of content and return every matching comment plus all of its descendants at any reply depth, preserving input order and omitting unrelated branches.
  5. CommentView(comments, storage) — Coordinate the UI state:
    • __init__(comments, storage) copies comments, loads (self.field, self.direction) from storage, and sets self.query = "".
    • set_sort(field, direction) validates and saves the new preference to storage before updating self.field and self.direction.
    • set_filter(query) updates self.query in memory only (filter text is not persisted across refreshes).
    • visible_tree() filters self.comments by self.query and 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 (int or str); userId values are mutually comparable.
  • timestamp is either an int/float epoch value or a valid ISO 8601 datetime string.
  • storage only stores str keys and str values, and may initially contain missing, malformed, or outdated JSON text under STORAGE_KEY.
  • Input lists and individual comment dictionaries passed by callers must never be mutated in place.

Step-by-step walkthrough

  1. 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 timestamp or userId in ascending ("asc") or descending ("desc") mode. 2. Persist the chosen sort setting so reloading the page restores it. 3. Assemble nested reply trees from flat parentId links. 4. Filter content case-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 have parentId: None.
    • Browser storage (storage): a string-to-string mapping modeling window.localStorage in 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 render
    

    Why filter before building the tree? Suppose comment 20 matches the search query while its parent comment 10 does not. After filter_comments, 20 and its reply 30 remain in the visible list while 10 is excluded. When build_tree sees that 20's parentId (10) is absent from the visible dictionary, it automatically promotes 20 (with 30 nested 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"
    
  2. Sort comments with instant comparison and stable tie-breaking

    Two subtle bugs trip up naive comment sorting:

    1. 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" equals 08: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 since 1970-01-01T00:00:00Z) compares exact instants.
    2. 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 smaller id in 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
    
  3. 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: localStorage only accepts strings. Saving a raw JavaScript object converts it into the useless text "[object Object]", so serialize {"field": field, "direction": direction} with json.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 to DEFAULT_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, direction
    
  4. Build 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,000 checks for 10,000 comments). We can build the entire nested tree in one dictionary pass after sorting:

    1. Create a lookup dictionary nodes mapping each comment["id"] to a fresh copy of that comment with "children": [].
    2. Iterate through sort_comments(comments, field, direction) in order. For each comment, look up its parent in nodes in O(1) time and append node to nodes[parent_id]["children"] (or to roots if it has no valid parent in nodes).

    Because we visit comments in the exact target sort order, roots and 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 20 safely attaches to nodes[10]["children"] before node 10 itself is appended to roots, because every node dictionary already exists in nodes from Phase 1. Also, any orphan node (a comment whose parentId is 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
    
  5. Filter matching comments and all their descendants

    Text filtering must retain every comment whose content contains 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):

    1. Build an adjacency list children_by_parent (a dictionary mapping each parent_id to a list of direct child_ids).
    2. Push every comment ID whose content contains the search text (using .casefold() for thorough case-insensitive matching) onto stack.
    3. Pop an ID from stack, skip it if it is already in visible_ids, otherwise add it to visible_ids and push all of its direct children onto stack.
    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_ids set 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 in O(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
    
  6. Connect everything inside CommentView

    CommentView wraps the exact state a frontend component manages: - On construction (initial load or page reload), it loads (self.field, self.direction) from storage and starts with an empty self.query. - set_sort calls save_sort_preference first so an invalid field or direction raises ValueError before mutating self.field or self.direction. - set_filter updates self.query in memory only (search text is transient, whereas sort preference persists). - visible_tree chains filter_comments into build_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, read window.localStorage inside useEffect after mount because window is 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>
      );
    }
    
  7. 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"
    
    1. Default load (timestamp, "desc"): Roots 10 (14:00) and 40 (13:15) appear newest-first. Under 10, reply 20 (14:06) appears above reply 50 (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)
    2. Select ("userId", "asc") and reload (Example 1): storage["comments.sort"] holds '{"field": "userId", "direction": "asc"}'. A fresh CommentView restores ("userId", "asc"). Roots 40 and 10 both belong to userId = 200, so the tie-breaker puts older 40 (13:15) before 10 (14:00); under 10, replies 50 (14:03) and 20 (14:06) both belong to userId = 100, so 50 appears before 20.
    3. Filter "AMPLIFICATION" (Example 2): Only comment 20 matches by text; DFS marks 20 and its child 30 visible ([20, 30]). In build_tree, 20's parentId (10) is not in nodes, so 20 lifts cleanly to a root with child 30 nested underneath, while thread 40 -> 60 disappears completely.
  8. 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 and O(n log n) comparisons) and returning a new n-element list.
  • build_tree — O(n log n) time, O(n) space: Creating the nodes dictionary copies all n comments once (O(n)), sorting takes O(n log n), and linking each node to its parent does one O(1) dictionary lookup per comment (O(n)). The nodes map and "children" lists hold n node dictionaries total.
  • filter_comments — O(n + L * q) time, O(n) space: Building the adjacency list (a map from each parent_id to its list of child_ids) scans n comments once, substring matching checks L total characters against a q-character needle (O(L * q) worst case, typically near O(L)), and the depth-first search (DFS) (stack-based downward traversal) visits each comment ID at most once thanks to visible_ids. The map, stack, and set store at most n IDs.
  • 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: Runs filter_comments followed by build_tree on the visible subset.

Edge cases

  • Empty comment list or zero filter matches: Both filter_comments and build_tree return [] 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_tree promotes the matching orphan node (a node whose parentId is 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_ids set skips any ID already visited, so no comment is duplicated or traversed twice.
  • Deleted parent (parentId = 999) or self-parenting bug (parentId == id): build_tree checks parent_id == comment_id or parent_id not in nodes and 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_comments terminates safely because visible_ids stops cycles, and build_tree finishes in one non-recursive pass (cyclic nodes have no root, so they stay detached from roots).
  • Ties on userId or timestamp: Always broken older-first (parse_timestamp), then by smaller id, in both "asc" and "desc" modes so rows never swap places unpredictably.
  • Mixed timezone offsets and naive timestamps: Converting through parse_timestamp into Unix epoch seconds (seconds since 1970-01-01T00:00:00Z) compares true instants; strings without an explicit offset default consistently to UTC.
  • Missing, corrupted, or outdated storage payloads: load_sort_preference catches missing keys, invalid JSON, non-dict JSON values (such as ["userId", "asc"]), and unknown fields/directions, returning DEFAULT_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 fast O(n) dictionary pass into an O(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 equal userIds).
  • Comparing raw timestamp strings: Fails whenever offsets differ ("+02:00" vs "Z").
  • Storing a raw object in localStorage without JSON serialization, or accessing window.localStorage unconditionally during server-side rendering (SSR) where window is 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 from build_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 to localStorage.

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 parentId pointers until hitting None or an already-marked node, tagging visited ancestors with "isContext": True. Because each node's parent pointer is traversed at most once when guarded by a visited set, the extra pass adds only O(n) time and O(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 by depth * 16px), pair the search box with debouncing (waiting ~200 ms after the user stops typing before recomputing), and precompute content.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 whenever localStorage.setItem modifies a key. Attaching a window.addEventListener("storage", ...) listener that checks event.key === STORAGE_KEY, runs the same defensive loadSortPreference validator, and updates component state keeps all open tabs synchronized safely.

Follow-up questions

Similar questions

More Bobyard interview questions

All 5 Bobyard questions →