Exit Discovery in a Locked Web Graph

Medium · Coding & Algorithms · Software Engineer · Technical Screen

Problem Statement

You are given an entry URL start_url into a web-hosted labyrinth where every URL represents a room and outgoing links represent one-way corridors. Determine whether any exit room can be opened starting from start_url, and return the URL of any such exit room (or None if none can be opened).

def find_exit(start_url: str, rooms: Dict[str, Dict]) -> Optional[str]:

In the test harness, the network service is modeled by the dictionary rooms. Fetching a url behaves according to these rules in order:

  1. Missing room (404): If url is not a key in rooms, the request fails with 404. Treat dead links as impassable without halting exploration of other paths.
  2. Temporary overload (503): If rooms[url] contains "busy": n (an optional integer), the first n requests sent to url fail with 503 before credentials are inspected. Retry 503 responses at least twice per fetch attempt (so any room with busy <= 2 succeeds on attempt 2 or 3), while capping retries so an indefinitely overloaded room never stalls your crawler.
  3. Token check (401): Once not overloaded, if rooms[url] contains "needs_key": k (an optional string), the request succeeds only when accompanied by header Authorization: Bearer <k>; otherwise it fails with 401.
  4. Opened room (200): Returns rooms[url], which provides:
    • "is_exit": bool — True when this room is a valid exit.
    • "neighbors": List[str] — outgoing room URLs linked from this room.
    • "key": str (optional) — an access token found inside this room. Different rooms may require different tokens, and you may discover a locked room on one branch before finding its required token on another branch, so retain every discovered token and revisit previously locked rooms when new tokens become available.

Corridors may form cycles or long chains, so your traversal must avoid infinite loops and call-stack overflow.

Examples

Example 1

Input:
  start_url = "https://labyrinth.test/entry"
  rooms = {
      "https://labyrinth.test/entry": {
          "is_exit": False,
          "neighbors": ["https://labyrinth.test/gate", "https://labyrinth.test/vault"],
      },
      "https://labyrinth.test/gate": {
          "is_exit": True,
          "neighbors": [],
          "busy": 1,
          "needs_key": "amber-9",
      },
      "https://labyrinth.test/vault": {
          "is_exit": False,
          "neighbors": [],
          "key": "amber-9",
      },
  }
Output: "https://labyrinth.test/gate"

Opening entry reveals gate and vault. Visiting gate first hits one 503 (busy = 1), retries into a 401 because "amber-9" has not been collected yet, and sets gate aside. Visiting vault yields "key": "amber-9", allowing gate to be re-fetched with Authorization: Bearer amber-9 and opened as an exit.

Example 2

Input:
  start_url = "https://labyrinth.test/hub"
  rooms = {
      "https://labyrinth.test/hub": {
          "is_exit": False,
          "neighbors": ["https://labyrinth.test/west", "https://labyrinth.test/ghost"],
      },
      "https://labyrinth.test/west": {
          "is_exit": False,
          "neighbors": ["https://labyrinth.test/hub"],
      },
  }
Output: None

ghost is missing (404), and hub and west point back and forth in a cycle with "is_exit": False, so the search terminates cleanly and returns None.

Constraints

  • 0 <= len(rooms) <= 10^4
  • Room graphs may contain self-loops, multi-room cycles, missing neighbor URLs, and chains of 5,000+ rooms.
  • When present, "busy" satisfies 0 <= busy <= 10^9.
  • When present, "key" and "needs_key" are strings.

Step-by-step walkthrough

  1. Understand the graph and HTTP rules

    Each URL identifies a room (a node in a directed graph) and neighbors lists outgoing corridors (directed edges). Starting at start_url, we must return the URL of any reachable room that opens with "is_exit": True, or None if none can be opened.

    Four obstacles shape the crawler:

    1. Cycles: hub can link to west while west links right back to hub.
    2. Dead links (404) and transient overloads (503): A room that answers 503 once or twice must be retried and crossed, whereas a room that answers 503 forever must eventually be skipped so the crawler never hangs.
    3. Per-room tokens (401): Different rooms may require different tokens, so discovering a second token k2 must not overwrite an earlier token k1 needed later.
    4. Reaching a locked door before its token: We may visit a locked room (401) on one branch (gate) and only discover its required token ("amber-9") later on another branch (vault).
  2. Base traversal: iterative BFS with a visited set

    Without 503 errors or 401 locks, finding an exit is standard Breadth-First Search (BFS) using a first-in, first-out queue (collections.deque) and a seen set:

    Cycle + dead-link example (Example 2): hub <-> west, hub -> ghost (404)
    
    1. Init:  queue = [hub], seen = {hub}
    2. Pop hub   -> 200; enqueue unseen west, ghost -> seen = {hub, west, ghost}
    3. Pop west  -> 200; neighbor hub IS in seen -> skip!
    4. Pop ghost -> 404; skip!
    5. queue is empty -> return None (terminates in 3 fetches instead of looping forever)
    

    Two implementation habits keep BFS fast and crash-free:

    • Use an explicit deque instead of recursion: a 5,000-room corridor overflows Python's ~1,000-frame recursion limit under recursive DFS, whereas a deque loop uses flat stack space.
    • Add URLs to seen when enqueueing, not when popping: if 50 rooms all link to the same hub URL, marking seen on enqueue puts that hub into queue once instead of 50 times.
  3. Simulate HTTP responses cleanly with `FakeMazeServer`

    To keep our crawler realistic — so you could swap in requests.Session in a live interview by changing three lines — we wrap rooms inside a tiny FakeMazeServer exposing server.get(url, headers) -> (status, body):

    • Missing URL -> (404, None).
    • Request number < room.get("busy", 0) -> (503, None) (an overloaded server fails before checking credentials).
    • Missing or wrong Authorization: Bearer <key> when needs_key is set -> (401, None).
    • Otherwise -> (200, room).
    MAX_ATTEMPTS = 3
    
    
    class FakeMazeServer:
        """Simulate HTTP GET responses from the in-memory `rooms` dictionary."""
    
        def __init__(self, rooms: Dict[str, Dict]):
            self.rooms = rooms
            # request_count: maps url -> int number of GET requests received so far
            self.request_count: Dict[str, int] = {}
    
        def get(self, url: str, headers: Dict[str, str]) -> Tuple[int, Optional[Dict]]:
            count = self.request_count.get(url, 0)
            self.request_count[url] = count + 1
    
            room = self.rooms.get(url)
            if room is None:
                return 404, None
    
            # A busy server fails with 503 for its first `busy` requests before checking auth.
            if count < room.get("busy", 0):
                return 503, None
    
            needed = room.get("needs_key")
            if needed is not None and headers.get("Authorization") != "Bearer " + needed:
                return 401, None
    
            return 200, room
    
  4. Retry transient `503` errors a bounded number of times

    When a single request gets 503, we retry the exact same (url, key) request up to MAX_ATTEMPTS = 3 times total (1 initial try + 2 retries):

    • If the room was only busy for 1 or 2 requests, attempt 2 or 3 gets the real status (200 or 401) and returns immediately.
    • If all 3 attempts return 503, we return (503, None) and let the crawler move on so a permanently overloaded room never stalls the search.
    • Statuses 200, 401, and 404 are deterministic for the same (url, key), so we never waste retries on them.
    def request_with_retries(
        server: FakeMazeServer, url: str, key: Optional[str]
    ) -> Tuple[int, Optional[Dict]]:
        """Send GET `url` with an optional Bearer key, retrying only transient 503 responses."""
        headers: Dict[str, str] = {}
        if key is not None:
            headers["Authorization"] = "Bearer " + key
    
        for _ in range(MAX_ATTEMPTS):
            status, body = server.get(url, headers)
            if status != 503:
                return status, body
    
        return 503, None
    
  5. Try untested keys and park `401` rooms until new keys arrive

    Now consider tokens and 401 responses:

    1. Keep a keyring keys (a list of all distinct tokens found so far): Because locks are per-room, Room X might need k1 even after we later pick up k2.
    2. Track tried_key_count[url] so each (room, key) pair is tested at most once: If url already failed 401 against keys[:2], then when a third token arrives we only need to test keys[2:]. When keys is still empty (has_any_keys == False), we send one unauthenticated request (key = None).
    3. Park 401 rooms in locked and wake them up when a new token is discovered: A 401 room is not permanently dead — we simply lack its token right now. Appending it to locked, and moving locked back into queue whenever a brand-new token enters keys, guarantees we re-check every locked door as soon as new credentials exist.
    State transitions for a room URL:
      discovered -> [queue] --(200, is_exit)--> RETURN url!
                       |    --(200, normal)---> collect key (wake `locked`), enqueue unseen neighbors
                       |    --(404 or 3x 503)-> drop permanently
                       v
                     (401)
                       |
                       v
                   [locked] --(whenever a NEW key is added to `keys`)--> back to [queue]!
    
    def fetch_room(
        server: FakeMazeServer, url: str, untested_keys: List[str], has_any_keys: bool
    ) -> Tuple[int, Optional[Dict]]:
        """Try `url` unauthenticated if we hold no keys yet, else try each untested key (newest first)."""
        if not has_any_keys:
            return request_with_retries(server, url, None)
    
        status, body = 401, None
        for key in reversed(untested_keys):
            status, body = request_with_retries(server, url, key)
            if status != 401:
                return status, body
        return status, body
    

    Why is termination still guaranteed? A room only enters locked on 401 (never after 200), so each of the V rooms opens with 200 at most once, hands out at most one new key (K <= V), and wakes locked at most K times total.

  6. Trace Example 1 step by step

    Let's trace Example 1 (entry links to gate with is_exit: True, busy: 1, needs_key: "amber-9", and vault with is_exit: False, key: "amber-9"):

    Step  Pop      Keys held     Server result              Queue after step     Locked after step
    ----------------------------------------------------------------------------------------------
    Init  -        []            -                          [entry]              []
    1     entry    []            200 (neighbors)            [gate, vault]        []
    2     gate     []            503 -> retry -> 401        [vault]              [gate]
    3     vault    []            200 (key="amber-9")        [gate] <-- woken!    []
    4     gate     ["amber-9"]   200 (is_exit=True)         -> returns ".../gate"!
    

    Notice step 2 -> step 3: gate first clears its transient 503 on attempt 2, hits 401 because "amber-9" is not yet held, waits safely in locked with tried_key_count[gate] = 0, and immediately wakes at step 3 when vault supplies "amber-9".

  7. Complete solution

    from typing import Any, Dict, List, Optional, Set, Tuple
    from collections import deque
    
    # One initial request plus up to two retries when a room answers 503 Service Unavailable.
    MAX_ATTEMPTS = 3
    
    
    class FakeMazeServer:
        """Simulate HTTP GET responses from the in-memory `rooms` dictionary."""
    
        def __init__(self, rooms: Dict[str, Dict]):
            self.rooms = rooms
            # request_count: maps url -> int number of GET requests received so far
            self.request_count: Dict[str, int] = {}
    
        def get(self, url: str, headers: Dict[str, str]) -> Tuple[int, Optional[Dict]]:
            count = self.request_count.get(url, 0)
            self.request_count[url] = count + 1
    
            room = self.rooms.get(url)
            if room is None:
                return 404, None
    
            # A busy server fails with 503 for its first `busy` requests before checking auth.
            if count < room.get("busy", 0):
                return 503, None
    
            needed = room.get("needs_key")
            if needed is not None and headers.get("Authorization") != "Bearer " + needed:
                return 401, None
    
            return 200, room
    
    
    def request_with_retries(
        server: FakeMazeServer, url: str, key: Optional[str]
    ) -> Tuple[int, Optional[Dict]]:
        """Send GET `url` with an optional Bearer key, retrying only transient 503 responses."""
        headers: Dict[str, str] = {}
        # Check `is not None` so even an empty-string key "" would still send the header.
        if key is not None:
            headers["Authorization"] = "Bearer " + key
    
        for _ in range(MAX_ATTEMPTS):
            status, body = server.get(url, headers)
            # 200, 401, and 404 are deterministic for this (url, key) pair, so return immediately.
            if status != 503:
                return status, body
    
        return 503, None
    
    
    def fetch_room(
        server: FakeMazeServer, url: str, untested_keys: List[str], has_any_keys: bool
    ) -> Tuple[int, Optional[Dict]]:
        """Try `url` unauthenticated if we hold no keys yet, else try each untested key (newest first)."""
        if not has_any_keys:
            return request_with_retries(server, url, None)
    
        status, body = 401, None
        for key in reversed(untested_keys):
            status, body = request_with_retries(server, url, key)
            if status != 401:
                return status, body
        return status, body
    
    
    def find_exit(start_url: str, rooms: Dict[str, Dict]) -> Optional[str]:
        server = FakeMazeServer(rooms)
    
        # queue: FIFO deque of room URLs waiting to be fetched
        queue = deque([start_url])
        # seen: every URL ever added to `queue` via graph discovery, preventing cycle loops
        seen: Set[str] = {start_url}
        # keys: list of distinct access keys collected so far, in discovery order
        keys: List[str] = []
        # locked: URLs that returned 401 for all keys available when we last tried them
        locked: List[str] = []
        # tried_key_count: maps url -> int count of entries in `keys` already tested on `url`
        tried_key_count: Dict[str, int] = {}
    
        while queue:
            url = queue.popleft()
            already_tried = tried_key_count.get(url, 0)
            untested_keys = keys[already_tried:]
    
            status, room = fetch_room(
                server, url, untested_keys, has_any_keys=len(keys) > 0
            )
    
            # Phase 1: Handle locked (401) and unreachable (404 / persistent 503) rooms.
            if status == 401:
                tried_key_count[url] = len(keys)
                locked.append(url)
                continue
            if status != 200 or room is None:
                continue
    
            # Phase 2: Check whether this opened room is an exit.
            if room.get("is_exit"):
                return url
    
            # Phase 3: Capture any newly discovered key and wake up previously locked rooms.
            new_key = room.get("key")
            if new_key is not None and new_key not in keys:
                keys.append(new_key)
                queue.extend(locked)
                locked = []
    
            # Phase 4: Enqueue unseen neighbor URLs.
            for neighbor in room.get("neighbors", []):
                if neighbor not in seen:
                    seen.add(neighbor)
                    queue.append(neighbor)
    
        return None
    

    ✅ Submit now — all tests should pass.

Intuition & how it works

Imagine exploring an unfamiliar building of connected rooms with three tools on your belt: a checklist of rooms you have already spotted (seen), a keyring (keys), and a notepad of locked doors you ran into earlier (locked). You explore room by room using Breadth-First Search (BFS) — a graph traversal that places discovered URLs at the back of a FIFO queue (a first-in, first-out line) and marks them in seen right away so circular corridors never trap you in an endless loop. If a door is temporarily jammed (503), you knock up to MAX_ATTEMPTS = 3 times before moving on; if a door has a badge reader (401) that rejects every token currently on your belt, you jot that URL onto locked. Whenever a later room awards a new token, you move every URL on locked back into your queue and test only the newly acquired tokens (keys[already_tried:]) against it.

Why do simpler attempts fail? Following outgoing links without a seen set loops forever on cycles (hub <-> west), and recursive Depth-First Search hits RecursionError on 5,000-room corridors. Once service errors and locks are added, retrying 503 without a cap hangs forever on an overloaded endpoint, discarding 401 URLs misses exits whose token sits down another branch, and keeping only a single latest_key variable fails whenever a room demands an older token collected several rooms back.

Here is a 4-step trace of Example 1 showing how queue, locked, and keys cooperate when a locked exit is visited before its token:

Graph: entry -> [gate (exit, busy=1, needs "amber-9"), vault (gives "amber-9")]

1. Pop entry (keys=[])             -> 200 OK              | queue=[gate, vault], locked=[]
2. Pop gate  (keys=[])             -> 503 then 401 Locked | queue=[vault],       locked=[gate]
3. Pop vault (keys=[])             -> 200, key="amber-9"  | keys=["amber-9"], locked woken -> queue=[gate]
4. Pop gate  (untested=["amber-9"])-> 200, EXIT!          | returns ".../gate"

Complexity

Let V be the number of distinct room URLs discovered (len(seen)), E be the total number of neighbor links across opened rooms, K be the number of distinct keys collected (K <= V), and R = MAX_ATTEMPTS (3).

  • Time and HTTP requests:
    • Unprotected graph (no 503s or keys): O(V + E) time and at most V requests. Because seen marks each URL the first time it enters queue, every URL is fetched once and every outgoing neighbors list is scanned once.
    • Full graph (with 503 retries and per-room keys): O(V * (K + 1) * R + E) time and at most V * (K + 1) * R simulated requests. Each URL is tried at most once unauthenticated (when keys is empty) and, because tried_key_count slices keys[already_tried:], at most once with each of the K distinct keys (K + 1 credential checks per URL, each sending at most R = 3 attempts on 503).
  • Space: O(V + K). seen, queue, locked, tried_key_count, and the simulated server's request_count each store at most V URLs, and keys stores at most K token strings, with O(1) call-stack depth because traversal is iterative.

Edge cases

  • start_url is already an exit: returns start_url immediately on the first 200 response.
  • start_url is missing (404) or rooms is empty: status != 200 skips it, the queue empties, and find_exit returns None.
  • Cycles and self-loops (west <-> hub, s -> s): seen blocks every duplicate neighbor link so each URL is discovered once.
  • Dead neighbor links (404): skipped cleanly without aborting other branches in queue.
  • Transient vs persistent 503: a room answering 503 once or twice succeeds on attempt 2 or 3 (MAX_ATTEMPTS = 3), whereas a room answering 503 forever is abandoned after 3 attempts.
  • Locked room visited before its token: parked in locked and re-queued automatically when a new token arrives.
  • Room needing an older token (k1 collected before k2): opened because keys retains every token ever collected rather than overwriting a single variable.
  • Locked exit whose token never appears: stays in locked after all reachable rooms finish, returning None.
  • Deep chains (5,000+ rooms): iterative deque avoids Python's recursion limit.

Common mistakes

  • Marking seen on pop instead of on enqueue: lets a room referenced by many neighbors enter queue dozens of times before its first fetch occurs.
  • Using recursive DFS: concise on tiny graphs, but raises RecursionError on chains deeper than ~1,000 rooms.
  • Unbounded while status == 503 retry loops: hangs forever if any reachable room never recovers.
  • Retrying 404 or 401 inside request_with_retries: a missing room or rejected Bearer token fails identically on immediate retry; only 503 is transient here.
  • Dropping 401 URLs permanently: fails whenever BFS reaches a locked door before exploring the branch holding its token.
  • Storing only the newest token (current_key = room["key"]): locks you out of rooms guarded by earlier tokens once another token is picked up.
  • Re-testing already-rejected tokens on every wake-up: without tried_key_count, a permanently locked room re-tests 1 + 2 + ... + K = O(K^2) tokens instead of O(K).

Alternative approaches

  • Deferred 503 re-queueing: Instead of firing all 3 attempts back-to-back on the same URL, track busy_retries[url] and push a 503 URL to the back of queue up to 2 times so other rooms are explored while the busy endpoint recovers (still enforcing a strict per-URL cap).
  • Iterative Depth-First Search (explicit list stack instead of deque): Because any reachable exit is accepted, popping from the end of a list (stack.pop()) is equally valid and uses the same O(V + K) memory, though BFS finds a minimum-hop exit whenever no rooms are locked.

Follow-up questions

  • How would you modify the crawler to return the complete sequence of room URLs from start_url to the discovered exit? Maintain a parent pointer map (parent[neighbor] = url — a dictionary recording which room first discovered each neighbor) at the moment neighbor enters seen, with parent[start_url] = None. Once a room opens with is_exit == True, walk backward via cur = parent[cur] until None and reverse the collected list; when no doors are locked, BFS guarantees this path has the fewest hops.
  • How would you accelerate exploration against a real network service where every HTTP round trip adds tens of milliseconds of latency? Because waiting on network I/O leaves the CPU idle, issue concurrent fetches with asyncio (for instance via httpx.AsyncClient) guarded by a semaphore (a concurrency counter such as asyncio.Semaphore(16) capping how many requests can be in flight simultaneously). Workers pull URLs from an asyncio.Queue, share seen, keys, and locked, and set an asyncio.Event as soon as any worker opens an exit so remaining in-flight tasks cancel immediately.
  • What backoff, header, and timeout safeguards belong in a production retry policy for 503 responses? Add exponential backoff with jitter — sleeping for a doubling base interval plus a small random offset (base * (2 ** attempt) + random.uniform(0, base)) so concurrent workers do not hammer a recovering server in synchronized waves. Honor any Retry-After HTTP header returned by the server, apply the same bounded retry policy to 429 Too Many Requests and socket timeouts, and enforce an overall wall-clock deadline on the crawl.

Follow-up questions

Similar questions

More Ramp interview questions

All 42 Ramp questions →