Top Teams from a Paginated HTTP Endpoint
Medium · Data Manipulation (SQL/Python) · Software Engineer · Online Assessment
Problem Statement
Implement get_top_teams to crawl a paginated HTTP standings endpoint, tolerate transient transport and rate-limit failures, discard malformed team entries, and return the names of the top n teams ranked by win count.
Response = Tuple[int, str, Dict[str, str]]
class FetchError(Exception):
...
def get_top_teams(
base_url: str,
n: int,
fetch: Callable[[str], Response] = http_get,
sleep: Callable[[float], None] = time.sleep,
max_attempts: int = 5,
base_delay: float = 0.5,
max_delay: float = 30.0,
max_pages: int = 10000,
) -> List[str]:
Pagination & URL Rules
- Pages are numbered sequentially starting at
1(1, 2, 3, ...). - Build each page URL by appending
page=<k>tobase_url:- Use
""(no extra delimiter) ifbase_urlalready ends with"?"or"&". - Otherwise use
"&"if"?"is already present inbase_url, or"?"ifbase_urlhas no query string yet.
- Use
- Stop crawling as soon as a request returns
HTTP 404, or returns a2xxstatus whose body is empty/whitespace-only, JSONnull, or an empty JSON array[]. - If crawling would advance past
max_pages(page > max_pages), raiseFetchError.
Error Handling, Retries, & Rate Limits
- Short-circuit & argument checks: If
max_attempts < 1, raiseValueError. Ifn <= 0, return[]immediately without callingfetch. - Retryable failures: Retry the current page (up to
max_attemptstotal tries for that page) whenfetchraisesOSError, returns an HTTP status in{408, 429, 500, 502, 503, 504}, or returns a2xxbody that fails JSON decoding. - Backoff &
Retry-After: Before each retry (never after the final failed attempt), callsleep:- If a retryable HTTP response provides a
Retry-Afterheader (matched case-insensitively) whose value parses as a finite float>= 0, sleepmin(seconds, max_delay). - Otherwise, sleep a uniform random duration in
[0, min(max_delay, base_delay * 2**attempt)], whereattemptis0after the first failed try,1after the second, and so on.
- If a retryable HTTP response provides a
- Unrecoverable failures: Raise
FetchErrorimmediately (without sleeping or retrying) on any other non-2xxstatus code (such as400,401,403) or when a2xxbody parses as valid JSON that is neithernullnor alist(for example, an error object{...}). Also raiseFetchErrorwhen allmax_attemptstries for a page fail.
Record Validation, Deduplication, & Ranking
- Keep an element of a page's JSON array only when it is a
dictwhose"name"is astrcontaining at least one non-whitespace character (name.strip() != "") and whose"wins"is a non-negativeint(explicitly rejectingboolvaluesTrueandFalse). Ignore any extra keys; skip invalid elements without terminating pagination. - If the same
"name"appears more than once across pages (or within a page), keep its maximum valid"wins"count. - Order unique valid teams by
winsdescending, breaking ties bynameascending (standard lexicographical order), and return at mostnteam names.
Examples
Example 1
Input:
- base_url = "https://stats.league.example/standings?division=west"
- n = 3
- Pages returned:
- ...&page=1 -> 200, [{"name": "Falcons", "wins": 11}, {"name": "Comets", "wins": 14}]
- ...&page=2 -> 200, [{"name": "Apex", "wins": 11}, {"name": "Drifters", "wins": 6}, {"name": "Falcons", "wins": 14}]
- ...&page=3 -> 200, []
Output: ["Comets", "Falcons", "Apex"]
Explanation: Because base_url already contains ?division=west, pages are requested with &page=1, &page=2, and &page=3. "Falcons" appears with 11 and 14 wins, keeping max(11, 14) = 14. Page 3 returns [], ending pagination. Sorting {"Comets": 14, "Falcons": 14, "Apex": 11, "Drifters": 6} by (-wins, name) places "Comets" ahead of "Falcons" alphabetically on their 14-win tie, followed by "Apex" (11), yielding ["Comets", "Falcons", "Apex"].
Example 2
Input:
- base_url = "https://stats.league.example/standings"
- n = 2
- Server sequence:
- ?page=1 (try 1) -> 429, body "", headers {"Retry-After": "3"}
- ?page=1 (try 2) -> 200, [{"name": "Titans", "wins": 8}, {"name": "", "wins": 20}, {"name": "Ravens", "wins": true}]
- ?page=2 -> 200, [{"name": "Orbit", "wins": 8}, {"name": "Vipers", "wins": -3}]
- ?page=3 -> 404, "Not Found"
Output: ["Orbit", "Titans"]
Explanation: With no ? in base_url, requests use ?page=1, ?page=2, and ?page=3. Page 1 is rate-limited on try 1, so the client sleeps 3.0 seconds per Retry-After and retries ?page=1. Blank "name", boolean "wins", and negative "wins" entries are skipped, leaving "Orbit" (8) and "Titans" (8). Page 3 returns 404, ending the crawl, and alphabetical tie-breaking returns ["Orbit", "Titans"].
Constraints
max_attempts >= 1(raiseValueErrorifmax_attempts < 1).base_delay >= 0.0andmax_delay >= 0.0.- If
n <= 0, zero HTTP requests are made and[]is returned. - If fewer than
nvalid distinct teams exist across all pages, return all valid distinct teams in ranked order. - Team names are preserved exactly as provided in
"name"(whitespace is checked only to reject empty/whitespace-only strings).
Step-by-step walkthrough
Restate the problem and make the code testable
We need
get_top_teams(base_url, n)to:- Request pages
1, 2, 3, ...by appendingpage=<number>tobase_urluntil an empty or missing page marks the end of the dataset. - Collect valid team objects
{"name": str, "wins": int}across all pages. - Sort teams by
winsdescending, breaking ties bynameascending, and return the topnteam names.
Because real HTTP APIs drop connections, return temporary
5xxerrors, enforce rate limits (HTTP 429), and occasionally emit bad records, we start with two clean engineering choices called dependency injection (passing external dependencies like network and clock functions as arguments with production defaults):- Inject
fetch(url) -> (status, body, headers): Production callshttp_get, while tests pass an in-memory fake server so every edge case runs offline in milliseconds. - Inject
sleep(seconds): Production callstime.sleep, while tests pass a recorder that logs wait times without actually pausing.
from typing import Any, Callable, Dict, List, Optional, Tuple import json import math import random import time # Response shape returned by fetch(url): (http_status_code, body_text, headers_dict) Response = Tuple[int, str, Dict[str, str]] class FetchError(Exception): """A page could not be fetched: retries ran out, or the server sent a permanent error."""State three practical assumptions up front so an interviewer can confirm them immediately: - End of pagination:
HTTP 404, an empty JSON array[], JSONnull, or a blank body (204/ whitespace) means there are no more pages. - Duplicate team names: If a row shifts between pages while we crawl and the same team appears twice, we keep its highestwinsvalue rather than double-counting it. - Unrecoverable page failure: If a page still fails after all retry attempts, we raiseFetchErrorrather than silently returning an incomplete top-nlist.- Request pages
Start with the naive loop and see where it breaks
On a perfect network with spotless JSON, the entire task would fit in a dozen lines:
def get_top_teams_naive(base_url, n, fetch): teams = [] page = 1 while True: status, body, headers = fetch(f"{base_url}&page={page}") if status == 404 or json.loads(body) == []: break teams.extend(json.loads(body)) page += 1 teams.sort(key=lambda t: (-t["wins"], t["name"])) return [t["name"] for t in teams[:n]]In production, almost every line here has a bug waiting to happen: - A brief socket reset on page
38of40crashes the whole run. - AnHTTP 429(rate limit) or503(service busy) returns an HTML or JSON error message;json.loadseither crashes or treats an error dict as team data. - One malformed record like{"name": "Falcons", "wins": null}crashessortwith aTypeError, and{"name": "Ravens", "wins": true}silently countsTrueas1win in Python. - Ifbase_urlhas no?yet (e.g.,"https://stats.league.example/standings"), appending"&page=1"builds an invalid URL. - If a buggy server ignorespageand returns page 1 forever,while Truenever terminates.Classify every HTTP response into four buckets
Before writing retry code, map every possible outcome of calling
fetch(url)to one of four clear actions:fetch(url) |-- HTTP 404, or 2xx with "", "[]", or "null" --> END OF DATA (return None) |-- 2xx with a valid JSON list [...] --> GOOD PAGE (return list) |-- OSError, HTTP 408/429/500/502/503/504, | or 2xx with truncated/invalid JSON --> TRANSIENT (sleep & retry) +-- HTTP 400/401/403, or 2xx JSON dict/number --> PERMANENT (raise FetchError now)Why separate transient from permanent errors? Retrying an
HTTP 401 Unauthorizedwill fail with the exact same bad credentials five times in a row while wasting time and rate-limit quota. By contrast, a dropped connection (OSError), gateway timeout (504), or truncated200body cut off mid-stream usually succeeds a second later.parse_pagehandles the2xxbody checks: it returnsNonefor end-of-data, returns the list for valid array pages, letsjson.JSONDecodeErrorbubble up so the caller retries truncated JSON, and raisesFetchErrorif valid JSON is not alist:def parse_page(body: str) -> Optional[List[Any]]: """Decode one 2xx page body into a list of raw records, or None when the page is empty.""" # Blank bodies, JSON null, and [] all mark the end of paginated results if body.strip() == "": return None data = json.loads(body) if data is None or data == []: return None # A valid JSON object like {"error": "bad query"} breaks the API contract; fail immediately if not isinstance(data, list): raise FetchError(f"expected a JSON array, got {type(data).__name__}") return dataAdd retries with Retry-After, exponential backoff, and jitter
When a transient failure happens, how long should we pause before trying again?
- Honor
Retry-Afterwhen present: Rate-limited (429) or overloaded (503) servers often send aRetry-Afterheader telling clients how many seconds to wait. Because HTTP headers are case-insensitive (Retry-Aftervs.retry-after), we matchkey.lower() == "retry-after", verify it parses as a finite non-negative number, and cap it atmax_delayso a misconfiguredRetry-After: 999999cannot hang our worker for days. - Fall back to exponential backoff with full jitter: On attempt
0, 1, 2, ..., double the maximum wait (base_delay * 2**attempt, capped atmax_delay), then draw a uniform random number between0and that cap. Randomizing (jitter) prevents a "thundering herd" where hundreds of clients that failed during the same blip wake up at the exact same millisecond and knock the recovering server down again. - Never sleep after the final failed attempt: Check
attempt + 1 < max_attemptsbefore callingsleep.
RETRYABLE_STATUSES = {408, 429, 500, 502, 503, 504} def retry_after_seconds(headers: Dict[str, str]) -> Optional[float]: """Parse a non-negative finite Retry-After header in seconds, or return None.""" # HTTP header names are case-insensitive ('Retry-After', 'retry-after', etc.) for key, value in headers.items(): if key.lower() == "retry-after": try: seconds = float(value) except (TypeError, ValueError): # Non-numeric values (such as HTTP date strings) fall back to exponential backoff return None if math.isfinite(seconds) and seconds >= 0: return seconds return None return None def backoff_delay(attempt: int, base_delay: float, max_delay: float) -> float: """Exponential backoff with full jitter in [0, min(max_delay, base_delay * 2**attempt)].""" # Full jitter spreads synchronized clients across [0, cap] so retries do not collide again delay_cap = min(max_delay, base_delay * (2 ** attempt)) return random.uniform(0.0, delay_cap) def fetch_page(url: str, fetch: Callable[[str], Response], sleep: Callable[[float], None], max_attempts: int, base_delay: float, max_delay: float) -> Optional[List[Any]]: """Fetch one page with bounded retries; return None for an empty or 404 end-of-data page.""" last_problem = "" for attempt in range(max_attempts): server_wait: Optional[float] = None try: status, body, headers = fetch(url) # 404 means we stepped past the final page of results if status == 404: return None if 200 <= status < 300: return parse_page(body) # Permanent client errors (400, 401, 403) will not recover on retry, so abort immediately if status not in RETRYABLE_STATUSES: raise FetchError(f"{url}: HTTP {status} is not retryable") last_problem = f"HTTP {status}" server_wait = retry_after_seconds(headers) except OSError as err: last_problem = f"network error: {err!r}" except json.JSONDecodeError: # A truncated 200 response from a dropped proxy connection is worth retrying last_problem = "body is not valid JSON" # Only sleep when at least one retry attempt remains if attempt + 1 < max_attempts: if server_wait is not None: sleep(min(server_wait, max_delay)) else: sleep(backoff_delay(attempt, base_delay, max_delay)) raise FetchError(f"{url}: giving up after {max_attempts} attempts ({last_problem})")- Honor
Validate each team record strictly
Real-world JSON payloads often contain nulls, missing keys, stringified numbers (
"5"), negative numbers, or booleans. Rather than crashing the whole job over one dirty row,parse_teamvalidates each item and returnsNonewhen a row should be skipped:recordmust be adict;namemust be astrcontaining at least one non-whitespace character;winsmust be a non-negativeint—excludingbool, because in Pythonboolis a subclass ofint(isinstance(True, int)evaluates toTrue, so forgetting this check turns{"wins": true}into1win!).
def parse_team(record: Any) -> Optional[Tuple[str, int]]: """Validate one team object and return (name, wins), or None if malformed.""" if not isinstance(record, dict): return None name = record.get("name") wins = record.get("wins") if not isinstance(name, str) or name.strip() == "": return None # Check isinstance(wins, bool) first because bool is a subclass of int in Python (True == 1) if isinstance(wins, bool) or not isinstance(wins, int) or wins < 0: return None return name, winsNotice an important pagination subtlety: if page
2contains only malformed records (e.g.,[{"name": ""}]),parse_pagestill returns a non-empty list,parse_teamskips the bad rows, and our loop continues to page3. Only a genuinely empty or404page ends pagination.Build URLs, merge pages, and sort by (-wins, name)
Now connect pagination, deduplication, and sorting in
get_top_teams:page_urlpicks"?"whenbase_urlhas no query string,"&"when it already has?division=west, and""ifbase_urlalready ends with?or&.best_winsmapsteam_name -> max_wins_seen, merging pages and deduplicating teams inO(1)average time per valid record.max_pagesstops runaway loops if a broken server ignorespageand serves page1forever.- Sorting
best_wins.items()with key(-wins, name)negates integerwinsso higher win counts come first while keeping stringnamein ascending alphabetical order ("Comets"before"Falcons"). Usingreverse=Trueon(wins, name)would wrongly reverse names ("Falcons"before"Comets").
def page_url(base_url: str, page: int) -> str: """Append page=<number> using '?' or '&' depending on whether base_url already has a query.""" if base_url.endswith(("?", "&")): separator = "" elif "?" in base_url: separator = "&" else: separator = "?" return f"{base_url}{separator}page={page}" def ranking_key(item: Tuple[str, int]) -> Tuple[int, str]: """Sort key ordering higher wins first (-wins) and breaking ties by name ascending.""" name, wins = item return (-wins, name)Trace Sample 1 and Sample 2
Walk through
get_top_teams("https://stats.league.example/standings?division=west", n=3)(with a429retry and a dirty row mixed in so every phase appears in one trace):Step Request URL Server outcome Action & best_wins state ---- --------------- -------------------------------------------------- ----------------------------------------------- 1 ...&page=1 HTTP 429, Header {"Retry-After": "3"} sleep(3.0), retry page 1 (attempt 2) 2 ...&page=1 200 [{"name":"Falcons","wins":11}, best_wins = {"Falcons": 11, "Comets": 14} {"name":"Comets","wins":14}] 3 ...&page=2 ConnectionError("socket reset") sleep(random in [0, 0.5]), retry page 2 4 ...&page=2 200 [{"name":"Apex","wins":11}, {"name":"","wins":9}, skip blank name; Falcons updates max(11,14)=14 {"name":"Drifters","wins":6}, best_wins = {"Falcons":14, "Comets":14, {"name":"Falcons","wins":14}] "Apex":11, "Drifters":6} 5 ...&page=3 200 [] parse_page -> None, exit pagination loop Sort best_wins by (-wins, name): ("Comets", 14) -> key (-14, "Comets") <-- "Comets" < "Falcons" breaks the tie at 14 wins ("Falcons", 14) -> key (-14, "Falcons") ("Apex", 11) -> key (-11, "Apex") ("Drifters", 6) -> key ( -6, "Drifters") Return top n=3 names: ["Comets", "Falcons", "Apex"]Complete solution
Put the default
urllibfetcher alongside all helpers andget_top_teams:from typing import Any, Callable, Dict, List, Optional, Tuple import json import math import random import time # Response shape returned by fetch(url): (http_status_code, body_text, headers_dict) Response = Tuple[int, str, Dict[str, str]] # Transient HTTP statuses worth retrying (timeout, rate limit, and gateway/server blips) RETRYABLE_STATUSES = {408, 429, 500, 502, 503, 504} class FetchError(Exception): """A page could not be fetched: retries ran out, or the server sent a permanent error.""" def http_get(url: str, timeout: float = 10.0) -> Response: """GET url and return (status, body, headers). Network failures raise OSError.""" # Imported inside the function so offline test sandboxes without sockets still load cleanly import http.client import urllib.error import urllib.request try: try: with urllib.request.urlopen(url, timeout=timeout) as resp: body = resp.read().decode("utf-8", "replace") return resp.status, body, dict(resp.headers) except urllib.error.HTTPError as err: # Close the error response socket after reading its status, body, and Retry-After header try: body = err.read().decode("utf-8", "replace") return err.code, body, dict(err.headers) finally: err.close() except http.client.HTTPException as err: # Convert dropped-stream errors (such as IncompleteRead) into OSError for retry handling raise ConnectionError(f"bad HTTP response: {err!r}") from err def page_url(base_url: str, page: int) -> str: """Append page=<number> using '?' or '&' depending on whether base_url already has a query.""" if base_url.endswith(("?", "&")): separator = "" elif "?" in base_url: separator = "&" else: separator = "?" return f"{base_url}{separator}page={page}" def retry_after_seconds(headers: Dict[str, str]) -> Optional[float]: """Parse a non-negative finite Retry-After header in seconds, or return None.""" # HTTP header names are case-insensitive ('Retry-After', 'retry-after', etc.) for key, value in headers.items(): if key.lower() == "retry-after": try: seconds = float(value) except (TypeError, ValueError): # Non-numeric values (such as HTTP date strings) fall back to exponential backoff return None if math.isfinite(seconds) and seconds >= 0: return seconds return None return None def backoff_delay(attempt: int, base_delay: float, max_delay: float) -> float: """Exponential backoff with full jitter in [0, min(max_delay, base_delay * 2**attempt)].""" # Full jitter spreads synchronized clients across [0, cap] so retries do not collide again delay_cap = min(max_delay, base_delay * (2 ** attempt)) return random.uniform(0.0, delay_cap) def parse_page(body: str) -> Optional[List[Any]]: """Decode one 2xx page body into a list of raw records, or None when the page is empty.""" # Blank bodies, JSON null, and [] all mark the end of paginated results if body.strip() == "": return None data = json.loads(body) if data is None or data == []: return None # A valid JSON object like {"error": "bad query"} breaks the API contract; fail immediately if not isinstance(data, list): raise FetchError(f"expected a JSON array, got {type(data).__name__}") return data def fetch_page(url: str, fetch: Callable[[str], Response], sleep: Callable[[float], None], max_attempts: int, base_delay: float, max_delay: float) -> Optional[List[Any]]: """Fetch one page with bounded retries; return None for an empty or 404 end-of-data page.""" last_problem = "" for attempt in range(max_attempts): server_wait: Optional[float] = None try: status, body, headers = fetch(url) # 404 means we stepped past the final page of results if status == 404: return None if 200 <= status < 300: return parse_page(body) # Permanent client errors (400, 401, 403) will not recover on retry, so abort immediately if status not in RETRYABLE_STATUSES: raise FetchError(f"{url}: HTTP {status} is not retryable") last_problem = f"HTTP {status}" server_wait = retry_after_seconds(headers) except OSError as err: last_problem = f"network error: {err!r}" except json.JSONDecodeError: # A truncated 200 response from a dropped proxy connection is worth retrying last_problem = "body is not valid JSON" # Only sleep when at least one retry attempt remains if attempt + 1 < max_attempts: if server_wait is not None: sleep(min(server_wait, max_delay)) else: sleep(backoff_delay(attempt, base_delay, max_delay)) raise FetchError(f"{url}: giving up after {max_attempts} attempts ({last_problem})") def parse_team(record: Any) -> Optional[Tuple[str, int]]: """Validate one team object and return (name, wins), or None if malformed.""" if not isinstance(record, dict): return None name = record.get("name") wins = record.get("wins") if not isinstance(name, str) or name.strip() == "": return None # Check isinstance(wins, bool) first because bool is a subclass of int in Python (True == 1) if isinstance(wins, bool) or not isinstance(wins, int) or wins < 0: return None return name, wins def ranking_key(item: Tuple[str, int]) -> Tuple[int, str]: """Sort key ordering higher wins first (-wins) and breaking ties by name ascending.""" name, wins = item return (-wins, name) def get_top_teams(base_url: str, n: int, fetch: Callable[[str], Response] = http_get, sleep: Callable[[float], None] = time.sleep, max_attempts: int = 5, base_delay: float = 0.5, max_delay: float = 30.0, max_pages: int = 10000) -> List[str]: """Names of the n teams with the most wins (ties: name ascending), over all pages.""" if max_attempts < 1: raise ValueError("max_attempts must be at least 1") # Avoid making network calls when zero or negative results are requested if n <= 0: return [] # best_wins: maps team_name -> highest valid win count seen across pages, e.g. {"Comets": 14} best_wins: Dict[str, int] = {} page = 1 # Phase 1: Crawl pages 1, 2, ... until an empty or 404 page signals end-of-data while True: if page > max_pages: raise FetchError(f"more than {max_pages} pages; is the server ignoring the page parameter?") records = fetch_page( page_url(base_url, page), fetch, sleep, max_attempts, base_delay, max_delay, ) if records is None: break # Phase 2: Validate records on this page and deduplicate teams by keeping max wins for record in records: team = parse_team(record) if team is None: continue name, wins = team if name not in best_wins or wins > best_wins[name]: best_wins[name] = wins page += 1 # Phase 3: Sort deduplicated teams by (-wins, name) and take the top n names ranked = sorted(best_wins.items(), key=ranking_key) top_names: List[str] = [] for name, wins in ranked[:n]: top_names.append(name) return top_names✅ Submit now — all tests should pass.
Intuition & how it works
Think of fetching paginated team standings like collecting score sheets from a clerk one folder (page=1, page=2, ...) at a time until the clerk hands you an empty folder or says "none left" (404). If the clerk says "give me 2 seconds" (HTTP 429 with a Retry-After header) or drops the phone (OSError / HTTP 503), you pause politely and ask for that exact same folder again rather than crashing or skipping it; if the clerk says "your badge is invalid" (HTTP 401), asking again is pointless so you stop immediately. As valid rows arrive, you keep a scoreboard dictionary best_wins[name] recording each team's highest win count, then sort once at the end by (-wins, name) to take the top n.
A naive while True loop that calls json.loads directly on every response fails in real production APIs within minutes. One transient gateway timeout (504) kills a 200-page job; an HTTP 429 error page gets parsed or crashes JSON decoding without backing off; one dirty row like {"name": "Comets", "wins": null} raises TypeError during sorting; and sorting with reverse=True reverses alphabetical tie-breaking from A-to-Z into Z-to-A.
Walk through Sample 1 and Sample 2 mechanics on a 2-page mini-trace with n = 2:
- Page 1 first returns HTTP 429 with Retry-After: 3, so we sleep 3.0 seconds and retry page 1. The retry returns [{"name": "Falcons", "wins": 11}, {"name": "Comets", "wins": 14}] -> best_wins = {"Falcons": 11, "Comets": 14}.
- Page 2 returns [{"name": "Apex", "wins": 11}, {"name": "", "wins": 20}, {"name": "Falcons", "wins": 14}] -> the blank name is skipped, "Apex" enters with 11, and "Falcons" updates to max(11, 14) = 14.
- Page 3 returns [] -> pagination stops. Sorting by (-wins, name) orders (-14, "Comets"), (-14, "Falcons"), (-11, "Apex"), returning ["Comets", "Falcons"].
Complexity
- CPU Time:
O(R + T log T), whereRis the total number of raw JSON items across all pages andTis the number of distinct valid team names (T <= R). We inspect each of theRitems once inO(1)average time to validate fields and update thebest_winshash map, then sort theTunique teams once inO(T log T)time. - Network & Wait Time: Fetching
Pnon-empty pages takesP + 1HTTP requests on the happy path (including the final empty/404sentinel page), and at mostmax_attempts * (P + 1)requests with retries. Each page sleeps at most(max_attempts - 1) * max_delayseconds (4 * 30s = 120swith defaults). - Space:
O(T + M), whereTis the number of distinct valid teams stored inbest_winsandMis the size of the single page currently being parsed in memory (previous raw page lists are discarded after each iteration).
Edge cases
n <= 0: Returns[]immediately without issuing a single HTTP request.nlarger than total valid teams (or zero pages of data): Slicingranked[:n]safely returns all available teams (or[]when page 1 is404or[]).- Base URL query formatting: Handles URLs without
?(?page=1), URLs with existing parameters (&page=1), and URLs already ending in?or&(page=1). - Ties on
wins: Negating numericwinsinside(-wins, name)sorts wins high-to-low while keeping string comparison in standard Unicode code-point ascending order ("Comets" < "Falcons", and uppercase"Vipers" < "apex"). - Duplicates across pages: Keeping
max(wins)makes deduplication independent of page arrival order and avoids double-counting rows duplicated by concurrent inserts during offset pagination. - Malformed records vs. empty pages: Non-dicts, blank/whitespace names, missing/negative/float/string
wins, and booleans (True/False) are skipped individually; a page full of malformed records is still non-empty, so pagination continues topage + 1. Retry-Afterquirks: Header matching is case-insensitive (retry-after), huge numeric values are capped atmax_delay, and non-numeric values (like HTTP date timestamps or"nan"/"inf") fall back cleanly to jittered exponential backoff.- Runaway pagination:
max_pagesraisesFetchErrorif a broken endpoint ignores thepagequery parameter and serves non-empty responses forever.
Common mistakes
- Retrying permanent
4xxerrors (400,401,403). Invalid credentials or malformed URLs never heal on retry; retrying them only burns quota and delays failure. - Exponential backoff without jitter. Without randomizing delays (
random.uniform(0, cap)), clients that fail during the same outage retry in lockstep waves (a thundering herd, where synchronized retries repeatedly overload a recovering server). - Sleeping after the final failed attempt. Waiting 16 seconds after
attempt == max_attempts - 1just makes error reporting slower without making another request. - Forgetting
isinstance(wins, bool)in Python. Becauseboolsubclassesint(isinstance(True, int)isTrue), omitting the boolean check accepts{"name": "X", "wins": true}as1win. - Using
sorted(..., key=lambda x: (x[1], x[0]), reverse=True).reverse=Trueflips both tuple elements, breaking ties in reverse alphabetical order (ZtoA) instead ofAtoZ. - Returning partial results when a middle page exhausts retries. Silently dropping page
7of20produces a plausible-looking wrong leaderboard that callers cannot detect. - Hardcoding live HTTP calls and
time.sleepinside unit tests. Passingfetchandsleepvia dependency injection lets tests verify429,503, timeouts, and exact wait bounds deterministically in milliseconds.
Alternative approaches
- Min-heap top-
nselection (heapq.nsmallest(n, best_wins.items(), key=ranking_key)): Replaces theO(T log T)full sort withO(T log n)heap selection—worthwhile whenTis in the millions andnis tiny (liken = 10). - Production HTTP retry adapters: Outside no-dependency interviews, libraries such as
urllib3.util.Retry(mounted on arequests.Session) ortenacityprovide battle-tested backoff andRetry-Afterparsing; writing the state machine explicitly in an interview proves you understand retry semantics under the hood.
Follow-up questions
- How would you speed this up by fetching pages concurrently without violating rate limits? Use a bounded worker pool (for example,
4concurrent workers) gated by a shared token bucket—a rate-limiter counter that refills tokens atRrequests per second and makes each worker wait for a token before callingfetch. Because the total page count is unknown up front, dispatch pages in small batches (1..4,5..8, ...) and stop scheduling new batches as soon as any page returns empty or404. Discard any already-fetched page whose number exceeds the lowest empty/404page number so the cutoff matches sequential pagination, and pause all workers globally whenever any worker receivesHTTP 429. - What happens if live games finish and rows move while you are paginating? Offset pagination (
page=kslices rows(k-1)*sizethroughk*size - 1of a changing table) suffers from page drift: an insert ahead of your cursor pushes a team down onto the next page so you see it twice (ourmaxdeduplication handles this), while a deletion pulls a team backward onto an already-read page so you miss it completely. The server-side fix is cursor (keyset) pagination—passing an opaque token like?after_id=last_seen_idor reading from a consistent point-in-time snapshot (?as_of=timestamp). - If there are 50 million distinct teams across pages and n = 10, how can you avoid O(T) memory? Because duplicate records for the same team keep the maximum win count rather than summing wins, a team's best record can compete on its own without accumulating history. Maintain a structure of at most
nentries (best_ndictionary plus worst-entry tracker): if an incoming(name, wins)is already inbest_n, update its wins upward if larger; otherwise insert it only if(-wins, name)beats the worst of thenheld teams (evicting that worst team). Any evicted team could only belong in the final topnif a later page has an even higher win count for it, in which case that later record will re-enter naturally—cutting memory fromO(T)toO(n)! (If duplicates had to be summed instead of maxed, streamingO(n)exact top-k is impossible because a team trailing on every page can add up to first place.)
Follow-up questions
- How would you speed this up by fetching pages concurrently without violating rate limits?
- What happens if live games finish and rows move while you are paginating?
- If there are 50 million distinct teams across pages and n = 10, how can you avoid O(T) memory?
Similar questions
- Fast Word Membership Lookup at Scale
- Palindromic Substring Count
- Job Posting Engagement Metrics Excluding Non-Viewing Applicants
- Compute 7-Day DAU, D1 Retention, and Revenue Cohorts
- Class-Level 2024 Exam Summary with Zero-Filled Averages
- Summarizing Imaging Claims Spend and Fiscal Months