Interactive Feed State with Author Lookup and Likes

Medium · Coding & Algorithms · Software Engineer · Online Assessment

Problem Statement

Implement BlogPage, the deterministic client-side state controller behind an interactive single-page article feed. Rather than performing live browser network sockets directly, BlogPage models asynchronous HTTP traffic explicitly so responses from multiple endpoints can resolve in any order.

Endpoints and Constants

  • POSTS_URL = "/api/posts" — returns a JSON list of post objects, each shaped as {"id": int, "title": str, "body": str, "authorId": int, "likes": int}.
  • ME_URL = "/api/me" — returns {"id": current_user_id} identifying the signed-in reader.
  • "/api/authors/<id>" — returns {"id": author_id, "name": str} for one writer.
  • UI display constants: LOADING_LABEL = "Loading...", UNKNOWN_AUTHOR = "Unknown author", and ERROR_MESSAGE = "Could not load posts.".

Class and Method Contract

from typing import Any, Dict, List, Optional


class BlogPage:
    def __init__(self) -> None: ...

    def start(self) -> List[str]: ...

    def on_response(self, url: str, ok: bool, data: Any = None) -> List[str]: ...

    def author_label(self, author_id: Any) -> str: ...

    def add_post(self, title: str, body: str) -> Optional[Dict[str, Any]]: ...

    def like(self, post_id: Any) -> bool: ...

    def render(self) -> Dict[str, Any]: ...

Feature Rules

  1. Lifecycle and parallel loading (__init__, start, on_response):
    • Before start(), the page is in "idle" status. Calling start() enters "loading" status and returns [POSTS_URL, ME_URL] so both requests launch concurrently.
    • on_response(url, ok, data) records one completed HTTP response (ok=False denotes a network or server error) and returns a list of follow-up URLs to request:
      • When POSTS_URL responds: if not ok or data is not a list, enter "error" status and return []. Otherwise copy the post dicts (do not mutate caller objects), sort them in descending order of "likes" (preserving existing relative order on ties), enter "ready" status, and return one "/api/authors/<authorId>" URL per distinct authorId not previously requested.
      • When ME_URL responds: mark the current-user request settled; record data.get("id") when ok and data is a dict (else None), and return [].
      • When a previously requested "/api/authors/<id>" URL responds: store data["name"] if ok, data is a dict, and data.get("name") is a non-blank string; otherwise store None to indicate lookup failure, and return [].
      • Raise ValueError if on_response receives any URL that was never requested.
  2. Flicker-free author resolution (author_label):
    • Until ME_URL has settled, return LOADING_LABEL ("Loading...") so a post never flashes a writer's name before switching to "You".
    • Once ME_URL has settled:
      • If the signed-in user's ID is not None and equals author_id, return "You" (regardless of whether "/api/authors/<author_id>" is pending or failed).
      • If author_id is None, return UNKNOWN_AUTHOR.
      • If author_id still awaits its author response, return LOADING_LABEL.
      • Otherwise return the writer's name, or UNKNOWN_AUTHOR if that lookup failed.
  3. Client-side post creation (add_post):
    • Trim whitespace from title and body. Return None without modifying state if status is not "ready", ME_URL has not settled, or either trimmed string is empty.
    • Otherwise create {"id": new_id, "title": clean_title, "body": clean_body, "authorId": me_id, "likes": 0} where new_id is 1 plus the largest existing post "id" (1 when the list is empty), append it while preserving stable descending "likes" order, and return the created dict.
  4. Interactive likes and stable ranking (like):
    • Increment "likes" by 1 on the post matching post_id, stably re-sort posts by "likes" descending so tied posts retain their prior relative display order (a post moves above another only once its "likes" is strictly higher), and return True. Return False if no post has post_id.
  5. View snapshot (render):
    • Return {"status": "idle"} or {"status": "loading"} before posts are ready.
    • Return {"status": "error", "message": ERROR_MESSAGE} on feed failure.
    • Return {"status": "ready", "posts": [{"id", "title", "body", "author", "likes"}, ...]} in current display order when ready.

Examples

Example 1

page = BlogPage()
page.start()  # -> ["/api/posts", "/api/me"]
page.on_response("/api/posts", True, [
    {"id": 10, "title": "Trail guide", "body": "Pack light", "authorId": 204, "likes": 2},
    {"id": 20, "title": "Camp stove", "body": "Boils fast", "authorId": 209, "likes": 4},
])  # -> ["/api/authors/209", "/api/authors/204"]
page.on_response("/api/me", True, {"id": 204})
page.on_response("/api/authors/204", True, {"id": 204, "name": "Maya"})
page.on_response("/api/authors/209", True, {"id": 209, "name": "Liam"})
page.render()

Output:

{
    "status": "ready",
    "posts": [
        {"id": 20, "title": "Camp stove", "body": "Boils fast", "author": "Liam", "likes": 4},
        {"id": 10, "title": "Trail guide", "body": "Pack light", "author": "You", "likes": 2},
    ],
}

Explanation: Post 20 (4 likes) sorts ahead of post 10 (2 likes). Because /api/me resolved to 204, post 10 displays "You", while post 20 displays "Liam".

Example 2

# Continuing from Example 1's loaded page:
page.like(10)   # post 10 -> 3 likes (stays below post 20)
page.like(10)   # post 10 -> 4 likes (tied with post 20; post 20 stays on top)
page.like(10)   # post 10 -> 5 likes (strictly higher; moves above post 20)
page.add_post(" Gear list ", " Tent and lamp ")
page.render()

Output:

{
    "status": "ready",
    "posts": [
        {"id": 10, "title": "Trail guide", "body": "Pack light", "author": "You", "likes": 5},
        {"id": 20, "title": "Camp stove", "body": "Boils fast", "author": "Liam", "likes": 4},
        {"id": 21, "title": "Gear list", "body": "Tent and lamp", "author": "You", "likes": 0},
    ],
}

Explanation: Post 10 overtakes post 20 only on the third click (5 > 4). Submitting the form trims whitespace, assigns collision-free ID 20 + 1 = 21 with 0 likes under user 204 ("You"), and places it at the bottom.

Constraints

  • Valid HTTP responses may arrive in any order consistent with request dependencies (/api/authors/<id> is sent only after /api/posts succeeds).
  • Any endpoint may fail (ok=False) or return malformed/incomplete JSON payloads.
  • Post lists contain up to several thousand items with non-negative integer "likes" and positive integer "id" values.

Step-by-step walkthrough

  1. Restate the four levels and model the UI state

    We are building a four-level single-page blog application: 1. Level 1: Render a list of posts (title and body). 2. Level 2: Add a form (title, body) that appends a new post (likes = 0, unique id) without reloading the page and clears the inputs. 3. Level 3: Load posts from GET /api/posts, fetch each author in parallel from GET /api/authors/:id, fetch the current user from GET /api/me, show "You" on the current user's posts or the author's name otherwise ("Unknown author" if that author request fails), and handle loading/error states. 4. Level 4: Add a Like button that immediately increments likes and keeps posts sorted in descending order of likes.

    Notice that the hardest bugs in front-end interviews have nothing to do with CSS—they are asynchronous state races: responses arriving out of order, duplicate author fetches, stale closures overwriting earlier answers, and tied posts jumping out of place.

    So we first model the exact page logic in a deterministic BlogPage state machine where network calls are explicit (start() returns outbound URLs, on_response(url, ok, data) delivers responses in any order, and render() returns the current view), and then translate that exact state machine into a clean React component.

  2. Fire independent API requests in parallel

    Let's map out which endpoints depend on which:

    Page load ─┬─► GET /api/posts ──┬─► GET /api/authors/209  (started together)
               │                    └─► GET /api/authors/204
               └─► GET /api/me      (started immediately alongside /api/posts)
    

    GET /api/posts and GET /api/me do not need data from each other, so start() launches both at the same time. Once /api/posts succeeds, we inspect the authorIds and fire one GET /api/authors/:id request per distinct authorId in parallel.

    Why does parallel + deduplicated fetching matter? Suppose each HTTP call takes 100 ms and 10 posts share 3 distinct authors: - Fetching /api/me, /api/posts, and all 10 author lookups one after another takes 12 * 100 ms = 1,200 ms. - Launching /api/posts + /api/me together (100 ms) and then the 3 unique authors together (100 ms) finishes in 200 ms!

    If GET /api/posts fails (ok=False or non-list payload), the page transitions to "error" and sends zero author requests.

    from typing import Any, Dict, List, Optional
    
    POSTS_URL = "/api/posts"
    ME_URL = "/api/me"
    
    
    class BlogPage:
        def __init__(self) -> None:
            # status: page lifecycle state ("idle" -> "loading" -> "ready" | "error")
            self.status: str = "idle"
            # posts: list of {"id", "title", "body", "authorId", "likes"} kept sorted by likes descending
            self.posts: List[Dict[str, Any]] = []
            # me_settled: True once GET /api/me has finished (whether it succeeded or failed)
            self.me_settled: bool = False
            # me_id: logged-in author's id from /api/me, or None if /api/me failed or has not finished
            self.me_id: Any = None
            # author_names: {authorId: "Maya" or None}, where None records a failed author lookup
            self.author_names: Dict[Any, Optional[str]] = {}
            # author_urls: {"/api/authors/204": 204} tracking in-flight/completed author URLs to avoid duplicates
            self.author_urls: Dict[str, Any] = {}
    
        def start(self) -> List[str]:
            """Begin initial load by requesting posts and current user concurrently."""
            self.status = "loading"
            return [POSTS_URL, ME_URL]
    
        def on_response(self, url: str, ok: bool, data: Any = None) -> List[str]:
            """Handle one asynchronous HTTP response and return any newly triggered requests."""
            if url == POSTS_URL:
                return self._on_posts(ok, data)
    
            if url == ME_URL:
                self.me_settled = True
                if ok and isinstance(data, dict):
                    self.me_id = data.get("id")
                else:
                    self.me_id = None
                return []
    
            if url in self.author_urls:
                author_id = self.author_urls[url]
                name: Optional[str] = None
                if ok and isinstance(data, dict):
                    raw_name = data.get("name")
                    if isinstance(raw_name, str) and raw_name.strip():
                        name = raw_name
                self.author_names[author_id] = name
                return []
    
            raise ValueError("response for a request that was never sent: " + url)
    
        def _on_posts(self, ok: bool, data: Any) -> List[str]:
            """Store fetched posts sorted by likes and return one lookup URL per unique authorId."""
            if not ok or not isinstance(data, list):
                self.status = "error"
                return []
    
            # Copy each post dict so liking or editing never mutates the caller's input objects
            copied_posts: List[Dict[str, Any]] = []
            for post in data:
                copied_posts.append(dict(post))
    
            self.posts = _sort_by_likes(copied_posts)
            self.status = "ready"
    
            # Deduplicate author lookups: four posts by author 204 trigger only one GET /api/authors/204
            follow_up_requests: List[str] = []
            for post in self.posts:
                author_id = post["authorId"]
                url = "/api/authors/" + str(author_id)
                if url not in self.author_urls:
                    self.author_urls[url] = author_id
                    follow_up_requests.append(url)
            return follow_up_requests
    
  3. Resolve author labels without UI flicker

    What should a post's author line display when /api/authors/204 finishes before /api/me? If we immediately showed "Maya" and 20 milliseconds later /api/me returned {"id": 204}, the label would visibly jump from "Maya" to "You".

    To eliminate that flicker and ensure every response arrival order ends in the exact same UI, author_label(author_id) evaluates five clear rules from top to bottom:

    1. If /api/me has not finished yet (not self.me_settled), show "Loading...".
    2. If author_id matches self.me_id, show "You"—even if /api/authors/<me_id> is still loading or failed!
    3. If author_id is None (which happens if the user adds a post after /api/me failed), show "Unknown author".
    4. If author_id is not in self.author_names yet, that author request is still in flight, so show "Loading..." while still displaying the post's title and body.
    5. Otherwise return the stored author name, or "Unknown author" if the lookup failed (None).
    from typing import Any
    
    LOADING_LABEL = "Loading..."
    UNKNOWN_AUTHOR = "Unknown author"
    
    
    class BlogPage:
        def author_label(self, author_id: Any) -> str:
            """Compute the display label for a post's author without UI flicker."""
            # Wait until /api/me settles so a post never flashes "Maya" before flipping to "You"
            if not self.me_settled:
                return LOADING_LABEL
    
            # Current user's posts always say "You", even if /api/authors/<me_id> is pending or failed
            if self.me_id is not None and author_id == self.me_id:
                return "You"
    
            # A post created locally after /api/me failed has author_id=None and no pending lookup
            if author_id is None:
                return UNKNOWN_AUTHOR
    
            if author_id not in self.author_names:
                return LOADING_LABEL
    
            resolved_name = self.author_names[author_id]
            if resolved_name is None:
                return UNKNOWN_AUTHOR
            return resolved_name
    
  4. Add client-side posts from the form (Level 2)

    When the user submits the form: - Strip leading/trailing whitespace from title and body, and ignore the submission if either field is empty, if posts are not "ready" yet, or if /api/me has not settled. - Generate a collision-free id by finding the largest existing post["id"] and adding 1 (starting from 1 if the list is empty). Using a naive counter starting at 1 would collide with existing server post IDs! - Set authorId = self.me_id and likes = 0, append the post, and keep the list sorted.

    from typing import Any, Dict, Optional
    
    
    class BlogPage:
        def add_post(self, title: str, body: str) -> Optional[Dict[str, Any]]:
            """Validate form fields and append a 0-like post owned by the current user."""
            clean_title = title.strip()
            clean_body = body.strip()
            if self.status != "ready" or not self.me_settled or clean_title == "" or clean_body == "":
                return None
    
            # Pick an id strictly larger than every existing post id so client ids never collide with server ids
            max_existing_id = 0
            for post in self.posts:
                if post["id"] > max_existing_id:
                    max_existing_id = post["id"]
            new_id = max_existing_id + 1
    
            new_post = {
                "id": new_id,
                "title": clean_title,
                "body": clean_body,
                "authorId": self.me_id,
                "likes": 0,
            }
            self.posts.append(new_post)
            # Stable sort keeps the new 0-like post after any existing 0-like posts
            self.posts = _sort_by_likes(self.posts)
            return new_post
    
  5. Increment likes and keep a stable descending order (Level 4)

    Liking a lower-ranked post should advance it past an upper post only when its like count strictly exceeds the upper post's count. That means when two posts reach a tie, their relative order must not flip!

    A stable sort (a sorting algorithm that preserves the existing relative order of items with equal sort keys) gives us this behavior automatically. Both Python's sorted(..., reverse=True) and modern JavaScript's Array.prototype.sort (since ES2019) are guaranteed stable:

    Initial display:        [Post 20 (4 likes), Post 10 (2 likes)]
    Click Like on Post 10:  [Post 20 (4 likes), Post 10 (3 likes)]
    Click Like on Post 10:  [Post 20 (4 likes), Post 10 (4 likes)]  <-- tie: Post 20 stays on top!
    Click Like on Post 10:  [Post 10 (5 likes), Post 20 (4 likes)]  <-- strictly higher: moves up!
    
    from typing import Any, Dict, List
    
    
    def _likes(post: Dict[str, Any]) -> int:
        return post["likes"]
    
    
    def _sort_by_likes(posts: List[Dict[str, Any]]) -> List[Dict[str, Any]]:
        # Python's sorted() uses Timsort, which is guaranteed stable even with reverse=True:
        # posts with equal likes keep their existing relative display order
        return sorted(posts, key=_likes, reverse=True)
    
    
    class BlogPage:
        def like(self, post_id: Any) -> bool:
            """Increment one post's likes and re-sort stably so ties do not swap order."""
            for post in self.posts:
                if post["id"] == post_id:
                    post["likes"] += 1
                    self.posts = _sort_by_likes(self.posts)
                    return True
            return False
    
  6. Render the view and trace out-of-order responses

    render() converts internal state into a clean view snapshot ("idle", "loading", "error", or "ready" with formatted posts). Let's trace an out-of-order arrival sequence where Liam's author record arrives before /api/me:

    1. start()
       Outbound: ["/api/posts", "/api/me"]
       render(): {"status": "loading"}
    
    2. on_response("/api/posts", ok=True, [post 10 (author 204, 2 likes), post 20 (author 209, 4 likes)])
       Outbound: ["/api/authors/209", "/api/authors/204"]
       render(): [post 20 (author="Loading...", likes=4), post 10 (author="Loading...", likes=2)]
    
    3. on_response("/api/authors/209", ok=True, {"id": 209, "name": "Liam"})
       render(): still "Loading..." on both posts because /api/me has not settled yet
    
    4. on_response("/api/me", ok=True, {"id": 204})
       render(): [post 20 (author="Liam", likes=4), post 10 (author="You", likes=2)]
    
    5. on_response("/api/authors/204", ok=True, {"id": 204, "name": "Maya"})
       render(): unchanged — post 10 already displays "You"
    
  7. Translate the state machine into JavaScript and React

    In a browser interview, this exact state machine maps directly onto React hooks. Watch out for four classic JavaScript/React traps: - fetch does not reject on HTTP 404 or 500: always check if (!response.ok) throw new Error(...). - Functional state updates (setAuthorNames(prev => ...)): multiple author promises resolve concurrently; reading authorNames directly inside .then(...) would use a stale closure from mount time and erase earlier authors. - Unmount cleanup (cancelled = true): ignores late responses if the component unmounts (or re-runs under React 18 StrictMode). - Stable list keys (key={post.id}): using post.id instead of the array index lets React reorder DOM nodes smoothly when likes changes.

    import { useEffect, useState } from "react";
    
    async function getJson(url) {
      const response = await fetch(url);
      if (!response.ok) {
        throw new Error(`${url} failed with HTTP ${response.status}`);
      }
      return response.json();
    }
    
    function sortByLikes(posts) {
      // Copy first so React state is never mutated in place; .sort() is stable in ES2019+
      return [...posts].sort((a, b) => b.likes - a.likes);
    }
    
    export default function BlogApp() {
      const [status, setStatus] = useState("loading");
      const [posts, setPosts] = useState([]);
      const [me, setMe] = useState({ settled: false, id: null });
      const [authorNames, setAuthorNames] = useState({});
      const [title, setTitle] = useState("");
      const [body, setBody] = useState("");
    
      useEffect(() => {
        let cancelled = false;
    
        // Start /api/me and /api/posts concurrently
        getJson("/api/me")
          .then((data) => {
            if (!cancelled) setMe({ settled: true, id: data?.id ?? null });
          })
          .catch(() => {
            if (!cancelled) setMe({ settled: true, id: null });
          });
    
        getJson("/api/posts")
          .then((data) => {
            if (cancelled) return;
            setPosts(sortByLikes(data));
            setStatus("ready");
    
            // Fetch each distinct authorId once, in parallel
            const uniqueAuthorIds = new Set(data.map((post) => post.authorId));
            for (const id of uniqueAuthorIds) {
              getJson(`/api/authors/${id}`)
                .then((author) => {
                  if (!cancelled) {
                    setAuthorNames((prev) => ({ ...prev, [id]: author?.name || null }));
                  }
                })
                .catch(() => {
                  if (!cancelled) {
                    setAuthorNames((prev) => ({ ...prev, [id]: null }));
                  }
                });
            }
          })
          .catch(() => {
            if (!cancelled) setStatus("error");
          });
    
        return () => {
          cancelled = true;
        };
      }, []);
    
      function authorLabel(authorId) {
        if (!me.settled) return "Loading...";
        if (me.id !== null && authorId === me.id) return "You";
        if (authorId === null) return "Unknown author";
        if (!(authorId in authorNames)) return "Loading...";
        return authorNames[authorId] ?? "Unknown author";
      }
    
      function handleSubmit(event) {
        event.preventDefault();
        const cleanTitle = title.trim();
        const cleanBody = body.trim();
        if (!cleanTitle || !cleanBody || !me.settled) return;
    
        setPosts((prev) => {
          let maxId = 0;
          for (const post of prev) {
            if (post.id > maxId) maxId = post.id;
          }
          const newPost = {
            id: maxId + 1,
            title: cleanTitle,
            body: cleanBody,
            authorId: me.id,
            likes: 0,
          };
          return sortByLikes([...prev, newPost]);
        });
        setTitle("");
        setBody("");
      }
    
      function handleLike(postId) {
        setPosts((prev) =>
          sortByLikes(
            prev.map((post) =>
              post.id === postId ? { ...post, likes: post.likes + 1 } : post
            )
          )
        );
      }
    
      if (status === "loading") return <p>Loading posts...</p>;
      if (status === "error") return <p role="alert">Could not load posts.</p>;
    
      return (
        <main>
          <form onSubmit={handleSubmit}>
            <input
              aria-label="Title"
              value={title}
              onChange={(e) => setTitle(e.target.value)}
            />
            <textarea
              aria-label="Body"
              value={body}
              onChange={(e) => setBody(e.target.value)}
            />
            <button type="submit" disabled={!me.settled}>Add post</button>
          </form>
          <ul>
            {posts.map((post) => (
              <li key={post.id}>
                <h2>{post.title}</h2>
                <p>{post.body}</p>
                <p>By {authorLabel(post.authorId)}</p>
                <p>
                  {post.likes} likes{" "}
                  <button type="button" onClick={() => handleLike(post.id)}>
                    Like
                  </button>
                </p>
              </li>
            ))}
          </ul>
        </main>
      );
    }
    
  8. Complete Python solution

    from typing import Any, Dict, List, Optional
    
    POSTS_URL = "/api/posts"
    ME_URL = "/api/me"
    LOADING_LABEL = "Loading..."
    UNKNOWN_AUTHOR = "Unknown author"
    ERROR_MESSAGE = "Could not load posts."
    
    
    def _likes(post: Dict[str, Any]) -> int:
        return post["likes"]
    
    
    def _sort_by_likes(posts: List[Dict[str, Any]]) -> List[Dict[str, Any]]:
        # Python's sorted() uses Timsort, which is guaranteed stable even with reverse=True:
        # posts with equal likes keep their existing relative display order
        return sorted(posts, key=_likes, reverse=True)
    
    
    class BlogPage:
        """State machine modeling the four-level blog UI independent of network arrival order."""
    
        def __init__(self) -> None:
            # status: page lifecycle state ("idle" -> "loading" -> "ready" | "error")
            self.status: str = "idle"
            # posts: list of {"id", "title", "body", "authorId", "likes"} kept sorted by likes descending
            self.posts: List[Dict[str, Any]] = []
            # me_settled: True once GET /api/me has finished (whether it succeeded or failed)
            self.me_settled: bool = False
            # me_id: logged-in author's id from /api/me, or None if /api/me failed or has not finished
            self.me_id: Any = None
            # author_names: {authorId: "Maya" or None}, where None records a failed author lookup
            self.author_names: Dict[Any, Optional[str]] = {}
            # author_urls: {"/api/authors/204": 204} tracking in-flight/completed author URLs to avoid duplicates
            self.author_urls: Dict[str, Any] = {}
    
        def start(self) -> List[str]:
            """Begin initial load by requesting posts and current user concurrently."""
            self.status = "loading"
            return [POSTS_URL, ME_URL]
    
        def on_response(self, url: str, ok: bool, data: Any = None) -> List[str]:
            """Handle one asynchronous HTTP response and return any newly triggered requests."""
            if url == POSTS_URL:
                return self._on_posts(ok, data)
    
            if url == ME_URL:
                self.me_settled = True
                if ok and isinstance(data, dict):
                    self.me_id = data.get("id")
                else:
                    self.me_id = None
                return []
    
            if url in self.author_urls:
                author_id = self.author_urls[url]
                name: Optional[str] = None
                if ok and isinstance(data, dict):
                    raw_name = data.get("name")
                    if isinstance(raw_name, str) and raw_name.strip():
                        name = raw_name
                self.author_names[author_id] = name
                return []
    
            raise ValueError("response for a request that was never sent: " + url)
    
        def _on_posts(self, ok: bool, data: Any) -> List[str]:
            """Store fetched posts sorted by likes and return one lookup URL per unique authorId."""
            if not ok or not isinstance(data, list):
                self.status = "error"
                return []
    
            # Copy each post dict so liking or editing never mutates the caller's input objects
            copied_posts: List[Dict[str, Any]] = []
            for post in data:
                copied_posts.append(dict(post))
    
            self.posts = _sort_by_likes(copied_posts)
            self.status = "ready"
    
            # Deduplicate author lookups: four posts by author 204 trigger only one GET /api/authors/204
            follow_up_requests: List[str] = []
            for post in self.posts:
                author_id = post["authorId"]
                url = "/api/authors/" + str(author_id)
                if url not in self.author_urls:
                    self.author_urls[url] = author_id
                    follow_up_requests.append(url)
            return follow_up_requests
    
        def author_label(self, author_id: Any) -> str:
            """Compute the display label for a post's author without UI flicker."""
            # Wait until /api/me settles so a post never flashes "Maya" before flipping to "You"
            if not self.me_settled:
                return LOADING_LABEL
    
            # Current user's posts always say "You", even if /api/authors/<me_id> is pending or failed
            if self.me_id is not None and author_id == self.me_id:
                return "You"
    
            # A post created locally after /api/me failed has author_id=None and no pending lookup
            if author_id is None:
                return UNKNOWN_AUTHOR
    
            if author_id not in self.author_names:
                return LOADING_LABEL
    
            resolved_name = self.author_names[author_id]
            if resolved_name is None:
                return UNKNOWN_AUTHOR
            return resolved_name
    
        def add_post(self, title: str, body: str) -> Optional[Dict[str, Any]]:
            """Validate form fields and append a 0-like post owned by the current user."""
            clean_title = title.strip()
            clean_body = body.strip()
            if self.status != "ready" or not self.me_settled or clean_title == "" or clean_body == "":
                return None
    
            # Pick an id strictly larger than every existing post id so client ids never collide with server ids
            max_existing_id = 0
            for post in self.posts:
                if post["id"] > max_existing_id:
                    max_existing_id = post["id"]
            new_id = max_existing_id + 1
    
            new_post = {
                "id": new_id,
                "title": clean_title,
                "body": clean_body,
                "authorId": self.me_id,
                "likes": 0,
            }
            self.posts.append(new_post)
            # Stable sort keeps the new 0-like post after any existing 0-like posts
            self.posts = _sort_by_likes(self.posts)
            return new_post
    
        def like(self, post_id: Any) -> bool:
            """Increment one post's likes and re-sort stably so ties do not swap order."""
            for post in self.posts:
                if post["id"] == post_id:
                    post["likes"] += 1
                    self.posts = _sort_by_likes(self.posts)
                    return True
            return False
    
        def render(self) -> Dict[str, Any]:
            """Produce a snapshot of what the UI displays right now."""
            if self.status == "error":
                return {"status": "error", "message": ERROR_MESSAGE}
            if self.status != "ready":
                return {"status": self.status}
    
            rendered_posts: List[Dict[str, Any]] = []
            for post in self.posts:
                rendered_posts.append({
                    "id": post["id"],
                    "title": post["title"],
                    "body": post["body"],
                    "author": self.author_label(post["authorId"]),
                    "likes": post["likes"],
                })
            return {"status": "ready", "posts": rendered_posts}
    

    ✅ Submit now — all tests should pass.

Intuition & how it works

Think of the blog page like a live newsroom bulletin board where messengers fetch different pieces of information at the same time: one fetches the list of articles (/api/posts), another checks your press badge ID (/api/me), and others look up each writer's name (/api/authors/:id). As cards sit on the board sorted from most-liked to least-liked, you hold off printing "Maya" vs "You" until your badge check returns so labels never flicker, and whenever a reader clicks Like, you move an article upward only when its likes strictly surpass the article above it.

A naive implementation fails in three ways. First, await-ing /api/posts, /api/me, and every post's /api/authors/:id one by one in a for loop turns 2 parallel network round trips into a slow waterfall of 2 + N sequential requests. Second, updating React state with { ...authorNames, [id]: name } inside async callbacks reads a stale closure (an older snapshot of a variable captured when the function was created), causing later author responses to erase earlier ones. Third, sorting without care for ties makes posts swap places prematurely when their like counts become equal.

Walk through the two sample posts (id=10 with authorId=204, likes=2 and id=20 with authorId=209, likes=4) when you are user 204: 1. On load, start() sends /api/posts and /api/me in parallel and renders "loading". 2. /api/posts returns both posts; we sort them to [post 20 (4 likes), post 10 (2 likes)] and fire /api/authors/209 and /api/authors/204 in parallel. 3. Once /api/me returns {"id": 204} and /api/authors/209 returns "Liam", post 20 displays "Liam" and post 10 displays "You". 4. Clicking Like on post 10 raises its likes to 3, then 4 (a tie—thanks to a stable sort, which preserves the existing relative order of equal-valued items, post 20 stays on top), and finally 5, moving post 10 above post 20.

Complexity

Let N be the number of posts on the page and A be the number of distinct authorIds (A <= N).

  • Initial load: O(N log N) CPU time and 2 network round-trip waves. Sorting the N posts by likes takes O(N log N) comparisons, and collecting unique authorIds with a hash map/set takes O(N) time. On the network (over HTTP/2), /api/posts and /api/me run in wave 1, and all A unique author requests run concurrently in wave 2, instead of 2 + N sequential round trips.
  • like(post_id): O(N log N) worst-case time (O(N) in practice). We scan up to N posts to increment the target post's likes and call _sort_by_likes. Because the list is already sorted except for one element that increased by 1, adaptive Timsort in Python and V8 finishes in O(N) comparisons.
  • add_post(title, body): O(N log N) worst-case time to scan for the maximum existing ID in O(N), append one 0-like post, and keep the list sorted.
  • render(): O(N) time to build one view dictionary per post with an O(1) dictionary lookup in author_label.
  • Space: O(N + A) memory to store the N post objects and at most A entries in author_names and author_urls.

Edge cases

  • GET /api/posts fails or returns invalid data: transitions to "error" ("Could not load posts."), sends zero author requests, and rejects add_post.
  • Individual GET /api/authors/:id fails: the post still renders with "Unknown author"; if that post belongs to me_id, it still displays "You" because we do not need the author's name.
  • GET /api/me fails: me_settled becomes True with me_id = None, so every post gracefully falls back to its author's name (or "Unknown author").
  • Out-of-order network responses: whether /api/me arrives first, between author lookups, or dead last, all 8 valid arrival permutations of the sample produce the exact same final view without flashing an author's name before "You".
  • Multiple posts by the same author: deduplicated via author_urls (or Set in JS) so each distinct author is fetched only once.
  • Ties in likes: equal like counts preserve their current display order; a post moves upward only when its likes become strictly greater.
  • Blank or whitespace-only form inputs: stripped and rejected without clearing user input or adding an empty post.

Common mistakes

  • Sequential await inside a for loop: writing for (const p of posts) { await fetch(...) } serializes every author request and stalls the UI.
  • Forgetting response.ok with browser fetch(): fetch() only rejects on network failures; HTTP 404 and 500 resolve normally unless you check if (!response.ok) throw ....
  • Stale state closures in React: calling setAuthorNames({ ...authorNames, [id]: name }) inside concurrent .then() handlers overwrites earlier authors; always use functional updates setAuthorNames((prev) => ({ ...prev, [id]: name })).
  • Mutating state arrays in place: calling posts.sort(...) or post.likes++ directly on React state mutates the existing array reference, causing React to skip re-rendering.
  • Using array index as React key (key={index}): when clicking Like reorders posts, index keys tie DOM state (focus, button active state) to row position rather than to the post itself; always use key={post.id}.
  • Using innerHTML with user-supplied title or body: opens a Cross-Site Scripting (XSS) vulnerability in plain JavaScript; use textContent or JSX auto-escaping.
  • Starting client-generated IDs at 1: collides with server post IDs 1, 2, ..., breaking like(post_id) and React keys.

Alternative approaches

  • Plain DOM JavaScript without a framework: store the exact same state fields (status, posts, me, authorNames) in a plain JS object, write a render() function that updates <ul id="posts"> using document.createElement and textContent, and call render() at the end of each event or response handler.
  • Promise.allSettled for all authors at once: waits until every author lookup finishes before updating authorNames once. That triggers fewer re-renders, at the cost of holding every author label at "Loading..." until the single slowest author request finishes or times out.

Follow-up questions

  • How would you save like clicks to the server without delaying UI feedback or double-counting retries? Use an optimistic UI update (updating the screen immediately on click before the server responds, then rolling back if the request fails): increment likes and re-sort right away, send POST /api/posts/:id/like in the background, and decrement likes via a functional state update if the request errors out. Attach a client-generated idempotency key (a unique request ID per click that the server remembers so retrying a timed-out request never counts the same click twice).
  • Which backend API change removes the fan-out of per-author HTTP requests on large feeds? Fetching a list of N items and then making separate requests for each item's related record is the N+1 request problem (one query for the list plus up to N follow-up queries, which saturates HTTP/1.1's 6-connection browser limit on large pages). Either have GET /api/posts embed author: { id, name } directly, or add a batch endpoint GET /api/authors?ids=204,209 so the client always finishes in at most two requests.
  • How would you add a Retry action on load failure and prevent late responses from an older load from corrupting newer state? Reset status to "loading" and re-run the fetch logic, while canceling any in-flight requests from the previous attempt using an AbortController (the standard browser API that passes an AbortSignal to fetch() so outdated requests can be aborted cleanly). Also tag each load attempt with a request generation counter so a late response from an aborted or superseded load can never overwrite newer state.

Follow-up questions

Similar questions

More Tripadvisor interview questions

All 1 Tripadvisor questions →