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", andERROR_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
- Lifecycle and parallel loading (
__init__,start,on_response):- Before
start(), the page is in"idle"status. Callingstart()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=Falsedenotes a network or server error) and returns a list of follow-up URLs to request:- When
POSTS_URLresponds: ifnot okordatais not alist, 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 distinctauthorIdnot previously requested. - When
ME_URLresponds: mark the current-user request settled; recorddata.get("id")whenokanddatais adict(elseNone), and return[]. - When a previously requested
"/api/authors/<id>"URL responds: storedata["name"]ifok,datais adict, anddata.get("name")is a non-blank string; otherwise storeNoneto indicate lookup failure, and return[]. - Raise
ValueErrorifon_responsereceives any URL that was never requested.
- When
- Before
- Flicker-free author resolution (
author_label):- Until
ME_URLhas settled, returnLOADING_LABEL("Loading...") so a post never flashes a writer's name before switching to"You". - Once
ME_URLhas settled:- If the signed-in user's ID is not
Noneand equalsauthor_id, return"You"(regardless of whether"/api/authors/<author_id>"is pending or failed). - If
author_id is None, returnUNKNOWN_AUTHOR. - If
author_idstill awaits its author response, returnLOADING_LABEL. - Otherwise return the writer's name, or
UNKNOWN_AUTHORif that lookup failed.
- If the signed-in user's ID is not
- Until
- Client-side post creation (
add_post):- Trim whitespace from
titleandbody. ReturnNonewithout modifying state if status is not"ready",ME_URLhas not settled, or either trimmed string is empty. - Otherwise create
{"id": new_id, "title": clean_title, "body": clean_body, "authorId": me_id, "likes": 0}wherenew_idis1plus the largest existing post"id"(1when the list is empty), append it while preserving stable descending"likes"order, and return the created dict.
- Trim whitespace from
- Interactive likes and stable ranking (
like):- Increment
"likes"by1on the post matchingpost_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 returnTrue. ReturnFalseif no post haspost_id.
- Increment
- 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.
- Return
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/postssucceeds). - 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
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 (
titleandbody). 2. Level 2: Add a form (title,body) that appends a new post (likes = 0, uniqueid) without reloading the page and clears the inputs. 3. Level 3: Load posts fromGET /api/posts, fetch each author in parallel fromGET /api/authors/:id, fetch the current user fromGET /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 aLikebutton that immediately incrementslikesand 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
BlogPagestate machine where network calls are explicit (start()returns outbound URLs,on_response(url, ok, data)delivers responses in any order, andrender()returns the current view), and then translate that exact state machine into a clean React component.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/postsandGET /api/medo not need data from each other, sostart()launches both at the same time. Once/api/postssucceeds, we inspect theauthorIds and fire oneGET /api/authors/:idrequest per distinctauthorIdin parallel.Why does parallel + deduplicated fetching matter? Suppose each HTTP call takes
100 msand 10 posts share 3 distinct authors: - Fetching/api/me,/api/posts, and all 10 author lookups one after another takes12 * 100 ms = 1,200 ms. - Launching/api/posts+/api/metogether (100 ms) and then the 3 unique authors together (100 ms) finishes in200 ms!If
GET /api/postsfails (ok=Falseor 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_requestsResolve author labels without UI flicker
What should a post's author line display when
/api/authors/204finishes before/api/me? If we immediately showed"Maya"and 20 milliseconds later/api/mereturned{"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:- If
/api/mehas not finished yet (not self.me_settled), show"Loading...". - If
author_idmatchesself.me_id, show"You"—even if/api/authors/<me_id>is still loading or failed! - If
author_id is None(which happens if the user adds a post after/api/mefailed), show"Unknown author". - If
author_idis not inself.author_namesyet, that author request is still in flight, so show"Loading..."while still displaying the post's title and body. - 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- If
Add client-side posts from the form (Level 2)
When the user submits the form: - Strip leading/trailing whitespace from
titleandbody, and ignore the submission if either field is empty, if posts are not"ready"yet, or if/api/mehas not settled. - Generate a collision-freeidby finding the largest existingpost["id"]and adding1(starting from1if the list is empty). Using a naive counter starting at1would collide with existing server post IDs! - SetauthorId = self.me_idandlikes = 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_postIncrement 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'sArray.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 FalseRender 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"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: -
fetchdoes not reject on HTTP 404 or 500: always checkif (!response.ok) throw new Error(...). - Functional state updates (setAuthorNames(prev => ...)): multiple author promises resolve concurrently; readingauthorNamesdirectly 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}): usingpost.idinstead of the array index lets React reorder DOM nodes smoothly whenlikeschanges.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> ); }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
Nposts by likes takesO(N log N)comparisons, and collecting uniqueauthorIds with a hash map/set takesO(N)time. On the network (over HTTP/2),/api/postsand/api/merun in wave 1, and allAunique author requests run concurrently in wave 2, instead of2 + Nsequential round trips. like(post_id): O(N log N) worst-case time (O(N) in practice). We scan up toNposts to increment the target post's likes and call_sort_by_likes. Because the list is already sorted except for one element that increased by1, adaptive Timsort in Python and V8 finishes inO(N)comparisons.add_post(title, body): O(N log N) worst-case time to scan for the maximum existing ID inO(N), append one 0-like post, and keep the list sorted.render(): O(N) time to build one view dictionary per post with anO(1)dictionary lookup inauthor_label.- Space: O(N + A) memory to store the
Npost objects and at mostAentries inauthor_namesandauthor_urls.
Edge cases
GET /api/postsfails or returns invalid data: transitions to"error"("Could not load posts."), sends zero author requests, and rejectsadd_post.- Individual
GET /api/authors/:idfails: the post still renders with"Unknown author"; if that post belongs tome_id, it still displays"You"because we do not need the author's name. GET /api/mefails:me_settledbecomesTruewithme_id = None, so every post gracefully falls back to its author's name (or"Unknown author").- Out-of-order network responses: whether
/api/mearrives 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(orSetin 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
awaitinside aforloop: writingfor (const p of posts) { await fetch(...) }serializes every author request and stalls the UI. - Forgetting
response.okwith browserfetch():fetch()only rejects on network failures; HTTP404and500resolve normally unless you checkif (!response.ok) throw .... - Stale state closures in React: calling
setAuthorNames({ ...authorNames, [id]: name })inside concurrent.then()handlers overwrites earlier authors; always use functional updatessetAuthorNames((prev) => ({ ...prev, [id]: name })). - Mutating state arrays in place: calling
posts.sort(...)orpost.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 clickingLikereorders posts, index keys tie DOM state (focus, button active state) to row position rather than to the post itself; always usekey={post.id}. - Using
innerHTMLwith user-suppliedtitleorbody: opens a Cross-Site Scripting (XSS) vulnerability in plain JavaScript; usetextContentor JSX auto-escaping. - Starting client-generated IDs at
1: collides with server post IDs1, 2, ..., breakinglike(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 arender()function that updates<ul id="posts">usingdocument.createElementandtextContent, and callrender()at the end of each event or response handler. Promise.allSettledfor all authors at once: waits until every author lookup finishes before updatingauthorNamesonce. 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
likesand re-sort right away, sendPOST /api/posts/:id/likein the background, and decrementlikesvia 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
Nitems and then making separate requests for each item's related record is the N+1 request problem (one query for the list plus up toNfollow-up queries, which saturates HTTP/1.1's 6-connection browser limit on large pages). Either haveGET /api/postsembedauthor: { id, name }directly, or add a batch endpointGET /api/authors?ids=204,209so 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
statusto"loading"and re-run the fetch logic, while canceling any in-flight requests from the previous attempt using anAbortController(the standard browser API that passes anAbortSignaltofetch()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
- How would you save like clicks to the server without delaying UI feedback or double-counting retries?
- Which backend API change removes the fan-out of per-author HTTP requests on large feeds?
- How would you add a Retry action on load failure and prevent late responses from an older load from corrupting newer state?
Similar questions
- 2D Max Pooling with Source Coordinates
- Time-Limited Credit Ledger
- Grid Path Scoring with Streak Bonuses
- Place One Hub to Minimize Maximum Grid Distance
- Increment Fixed-Size Digit Array by One
- Increment Digit Array