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> to base_url:
    • Use "" (no extra delimiter) if base_url already ends with "?" or "&".
    • Otherwise use "&" if "?" is already present in base_url, or "?" if base_url has no query string yet.
  • Stop crawling as soon as a request returns HTTP 404, or returns a 2xx status whose body is empty/whitespace-only, JSON null, or an empty JSON array [].
  • If crawling would advance past max_pages (page > max_pages), raise FetchError.

Error Handling, Retries, & Rate Limits

  • Short-circuit & argument checks: If max_attempts < 1, raise ValueError. If n <= 0, return [] immediately without calling fetch.
  • Retryable failures: Retry the current page (up to max_attempts total tries for that page) when fetch raises OSError, returns an HTTP status in {408, 429, 500, 502, 503, 504}, or returns a 2xx body that fails JSON decoding.
  • Backoff & Retry-After: Before each retry (never after the final failed attempt), call sleep:
    • If a retryable HTTP response provides a Retry-After header (matched case-insensitively) whose value parses as a finite float >= 0, sleep min(seconds, max_delay).
    • Otherwise, sleep a uniform random duration in [0, min(max_delay, base_delay * 2**attempt)], where attempt is 0 after the first failed try, 1 after the second, and so on.
  • Unrecoverable failures: Raise FetchError immediately (without sleeping or retrying) on any other non-2xx status code (such as 400, 401, 403) or when a 2xx body parses as valid JSON that is neither null nor a list (for example, an error object {...}). Also raise FetchError when all max_attempts tries for a page fail.

Record Validation, Deduplication, & Ranking

  • Keep an element of a page's JSON array only when it is a dict whose "name" is a str containing at least one non-whitespace character (name.strip() != "") and whose "wins" is a non-negative int (explicitly rejecting bool values True and False). 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 wins descending, breaking ties by name ascending (standard lexicographical order), and return at most n team 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 (raise ValueError if max_attempts < 1).
  • base_delay >= 0.0 and max_delay >= 0.0.
  • If n <= 0, zero HTTP requests are made and [] is returned.
  • If fewer than n valid 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

  1. Restate the problem and make the code testable

    We need get_top_teams(base_url, n) to:

    1. Request pages 1, 2, 3, ... by appending page=<number> to base_url until an empty or missing page marks the end of the dataset.
    2. Collect valid team objects {"name": str, "wins": int} across all pages.
    3. Sort teams by wins descending, breaking ties by name ascending, and return the top n team names.

    Because real HTTP APIs drop connections, return temporary 5xx errors, 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 calls http_get, while tests pass an in-memory fake server so every edge case runs offline in milliseconds.
    • Inject sleep(seconds): Production calls time.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 [], JSON null, 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 highest wins value rather than double-counting it. - Unrecoverable page failure: If a page still fails after all retry attempts, we raise FetchError rather than silently returning an incomplete top-n list.

  2. 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 38 of 40 crashes the whole run. - An HTTP 429 (rate limit) or 503 (service busy) returns an HTML or JSON error message; json.loads either crashes or treats an error dict as team data. - One malformed record like {"name": "Falcons", "wins": null} crashes sort with a TypeError, and {"name": "Ravens", "wins": true} silently counts True as 1 win in Python. - If base_url has no ? yet (e.g., "https://stats.league.example/standings"), appending "&page=1" builds an invalid URL. - If a buggy server ignores page and returns page 1 forever, while True never terminates.

  3. 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 Unauthorized will 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 truncated 200 body cut off mid-stream usually succeeds a second later.

    parse_page handles the 2xx body checks: it returns None for end-of-data, returns the list for valid array pages, lets json.JSONDecodeError bubble up so the caller retries truncated JSON, and raises FetchError if valid JSON is not a list:

    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
    
  4. Add retries with Retry-After, exponential backoff, and jitter

    When a transient failure happens, how long should we pause before trying again?

    1. Honor Retry-After when present: Rate-limited (429) or overloaded (503) servers often send a Retry-After header telling clients how many seconds to wait. Because HTTP headers are case-insensitive (Retry-After vs. retry-after), we match key.lower() == "retry-after", verify it parses as a finite non-negative number, and cap it at max_delay so a misconfigured Retry-After: 999999 cannot hang our worker for days.
    2. Fall back to exponential backoff with full jitter: On attempt 0, 1, 2, ..., double the maximum wait (base_delay * 2**attempt, capped at max_delay), then draw a uniform random number between 0 and 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.
    3. Never sleep after the final failed attempt: Check attempt + 1 < max_attempts before calling sleep.
    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})")
    
  5. 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_team validates each item and returns None when a row should be skipped:

    • record must be a dict;
    • name must be a str containing at least one non-whitespace character;
    • wins must be a non-negative int—excluding bool, because in Python bool is a subclass of int (isinstance(True, int) evaluates to True, so forgetting this check turns {"wins": true} into 1 win!).
    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
    

    Notice an important pagination subtlety: if page 2 contains only malformed records (e.g., [{"name": ""}]), parse_page still returns a non-empty list, parse_team skips the bad rows, and our loop continues to page 3. Only a genuinely empty or 404 page ends pagination.

  6. Build URLs, merge pages, and sort by (-wins, name)

    Now connect pagination, deduplication, and sorting in get_top_teams:

    • page_url picks "?" when base_url has no query string, "&" when it already has ?division=west, and "" if base_url already ends with ? or &.
    • best_wins maps team_name -> max_wins_seen, merging pages and deduplicating teams in O(1) average time per valid record.
    • max_pages stops runaway loops if a broken server ignores page and serves page 1 forever.
    • Sorting best_wins.items() with key (-wins, name) negates integer wins so higher win counts come first while keeping string name in ascending alphabetical order ("Comets" before "Falcons"). Using reverse=True on (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)
    
  7. Trace Sample 1 and Sample 2

    Walk through get_top_teams("https://stats.league.example/standings?division=west", n=3) (with a 429 retry 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"]
    
  8. Complete solution

    Put the default urllib fetcher alongside all helpers and get_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), where R is the total number of raw JSON items across all pages and T is the number of distinct valid team names (T <= R). We inspect each of the R items once in O(1) average time to validate fields and update the best_wins hash map, then sort the T unique teams once in O(T log T) time.
  • Network & Wait Time: Fetching P non-empty pages takes P + 1 HTTP requests on the happy path (including the final empty/404 sentinel page), and at most max_attempts * (P + 1) requests with retries. Each page sleeps at most (max_attempts - 1) * max_delay seconds (4 * 30s = 120s with defaults).
  • Space: O(T + M), where T is the number of distinct valid teams stored in best_wins and M is 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.
  • n larger than total valid teams (or zero pages of data): Slicing ranked[:n] safely returns all available teams (or [] when page 1 is 404 or []).
  • 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 numeric wins inside (-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 to page + 1.
  • Retry-After quirks: Header matching is case-insensitive (retry-after), huge numeric values are capped at max_delay, and non-numeric values (like HTTP date timestamps or "nan" / "inf") fall back cleanly to jittered exponential backoff.
  • Runaway pagination: max_pages raises FetchError if a broken endpoint ignores the page query parameter and serves non-empty responses forever.

Common mistakes

  • Retrying permanent 4xx errors (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 - 1 just makes error reporting slower without making another request.
  • Forgetting isinstance(wins, bool) in Python. Because bool subclasses int (isinstance(True, int) is True), omitting the boolean check accepts {"name": "X", "wins": true} as 1 win.
  • Using sorted(..., key=lambda x: (x[1], x[0]), reverse=True). reverse=True flips both tuple elements, breaking ties in reverse alphabetical order (Z to A) instead of A to Z.
  • Returning partial results when a middle page exhausts retries. Silently dropping page 7 of 20 produces a plausible-looking wrong leaderboard that callers cannot detect.
  • Hardcoding live HTTP calls and time.sleep inside unit tests. Passing fetch and sleep via dependency injection lets tests verify 429, 503, timeouts, and exact wait bounds deterministically in milliseconds.

Alternative approaches

  • Min-heap top-n selection (heapq.nsmallest(n, best_wins.items(), key=ranking_key)): Replaces the O(T log T) full sort with O(T log n) heap selection—worthwhile when T is in the millions and n is tiny (like n = 10).
  • Production HTTP retry adapters: Outside no-dependency interviews, libraries such as urllib3.util.Retry (mounted on a requests.Session) or tenacity provide battle-tested backoff and Retry-After parsing; 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, 4 concurrent workers) gated by a shared token bucket—a rate-limiter counter that refills tokens at R requests per second and makes each worker wait for a token before calling fetch. 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 or 404. Discard any already-fetched page whose number exceeds the lowest empty/404 page number so the cutoff matches sequential pagination, and pause all workers globally whenever any worker receives HTTP 429.
  • What happens if live games finish and rows move while you are paginating? Offset pagination (page=k slices rows (k-1)*size through k*size - 1 of 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 (our max deduplication 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_id or 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 n entries (best_n dictionary plus worst-entry tracker): if an incoming (name, wins) is already in best_n, update its wins upward if larger; otherwise insert it only if (-wins, name) beats the worst of the n held teams (evicting that worst team). Any evicted team could only belong in the final top n if a later page has an even higher win count for it, in which case that later record will re-enter naturally—cutting memory from O(T) to O(n)! (If duplicates had to be summed instead of maxed, streaming O(n) exact top-k is impossible because a team trailing on every page can add up to first place.)

Follow-up questions

Similar questions

More Reevo interview questions

All 3 Reevo questions →