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:
- Missing room (
404): Ifurlis not a key inrooms, the request fails with404. Treat dead links as impassable without halting exploration of other paths. - Temporary overload (
503): Ifrooms[url]contains"busy": n(an optional integer), the firstnrequests sent tourlfail with503before credentials are inspected. Retry503responses at least twice per fetch attempt (so any room withbusy <= 2succeeds on attempt2or3), while capping retries so an indefinitely overloaded room never stalls your crawler. - Token check (
401): Once not overloaded, ifrooms[url]contains"needs_key": k(an optional string), the request succeeds only when accompanied by headerAuthorization: Bearer <k>; otherwise it fails with401. - Opened room (
200): Returnsrooms[url], which provides:"is_exit": bool—Truewhen 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"satisfies0 <= busy <= 10^9. - When present,
"key"and"needs_key"are strings.
Step-by-step walkthrough
Understand the graph and HTTP rules
Each URL identifies a room (a node in a directed graph) and
neighborslists outgoing corridors (directed edges). Starting atstart_url, we must return the URL of any reachable room that opens with"is_exit": True, orNoneif none can be opened.Four obstacles shape the crawler:
- Cycles:
hubcan link towestwhilewestlinks right back tohub. - Dead links (
404) and transient overloads (503): A room that answers503once or twice must be retried and crossed, whereas a room that answers503forever must eventually be skipped so the crawler never hangs. - Per-room tokens (
401): Different rooms may require different tokens, so discovering a second tokenk2must not overwrite an earlier tokenk1needed later. - 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).
- Cycles:
Base traversal: iterative BFS with a visited set
Without
503errors or401locks, finding an exit is standard Breadth-First Search (BFS) using a first-in, first-out queue (collections.deque) and aseenset: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
dequeinstead of recursion: a 5,000-room corridor overflows Python's ~1,000-frame recursion limit under recursive DFS, whereas adequeloop uses flat stack space. - Add URLs to
seenwhen enqueueing, not when popping: if 50 rooms all link to the same hub URL, markingseenon enqueue puts that hub intoqueueonce instead of 50 times.
- Use an explicit
Simulate HTTP responses cleanly with `FakeMazeServer`
To keep our crawler realistic — so you could swap in
requests.Sessionin a live interview by changing three lines — we wraproomsinside a tinyFakeMazeServerexposingserver.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>whenneeds_keyis 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- Missing URL ->
Retry transient `503` errors a bounded number of times
When a single request gets
503, we retry the exact same(url, key)request up toMAX_ATTEMPTS = 3times 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 (
200or401) 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, and404are 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- If the room was only busy for 1 or 2 requests, attempt 2 or 3 gets the real status (
Try untested keys and park `401` rooms until new keys arrive
Now consider tokens and
401responses:- Keep a keyring
keys(a list of all distinct tokens found so far): Because locks are per-room, Room X might needk1even after we later pick upk2. - Track
tried_key_count[url]so each(room, key)pair is tested at most once: Ifurlalready failed401againstkeys[:2], then when a third token arrives we only need to testkeys[2:]. Whenkeysis still empty (has_any_keys == False), we send one unauthenticated request (key = None). - Park
401rooms inlockedand wake them up when a new token is discovered: A401room is not permanently dead — we simply lack its token right now. Appending it tolocked, and movinglockedback intoqueuewhenever a brand-new token enterskeys, 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, bodyWhy is termination still guaranteed? A room only enters
lockedon401(never after200), so each of theVrooms opens with200at most once, hands out at most one new key (K <= V), and wakeslockedat mostKtimes total.- Keep a keyring
Trace Example 1 step by step
Let's trace Example 1 (
entrylinks togatewithis_exit: True, busy: 1, needs_key: "amber-9", andvaultwithis_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:
gatefirst clears its transient503on attempt 2, hits401because"amber-9"is not yet held, waits safely inlockedwithtried_key_count[gate] = 0, and immediately wakes at step 3 whenvaultsupplies"amber-9".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 mostVrequests. Becauseseenmarks each URL the first time it entersqueue, every URL is fetched once and every outgoingneighborslist is scanned once. - Full graph (with
503retries and per-room keys):O(V * (K + 1) * R + E)time and at mostV * (K + 1) * Rsimulated requests. Each URL is tried at most once unauthenticated (whenkeysis empty) and, becausetried_key_countsliceskeys[already_tried:], at most once with each of theKdistinct keys (K + 1credential checks per URL, each sending at mostR = 3attempts on503).
- Unprotected graph (no
- Space:
O(V + K).seen,queue,locked,tried_key_count, and the simulated server'srequest_counteach store at mostVURLs, andkeysstores at mostKtoken strings, withO(1)call-stack depth because traversal is iterative.
Edge cases
start_urlis already an exit: returnsstart_urlimmediately on the first200response.start_urlis missing (404) orroomsis empty:status != 200skips it, the queue empties, andfind_exitreturnsNone.- Cycles and self-loops (
west <-> hub,s -> s):seenblocks every duplicate neighbor link so each URL is discovered once. - Dead neighbor links (
404): skipped cleanly without aborting other branches inqueue. - Transient vs persistent
503: a room answering503once or twice succeeds on attempt 2 or 3 (MAX_ATTEMPTS = 3), whereas a room answering503forever is abandoned after 3 attempts. - Locked room visited before its token: parked in
lockedand re-queued automatically when a new token arrives. - Room needing an older token (
k1collected beforek2): opened becausekeysretains every token ever collected rather than overwriting a single variable. - Locked exit whose token never appears: stays in
lockedafter all reachable rooms finish, returningNone. - Deep chains (5,000+ rooms): iterative
dequeavoids Python's recursion limit.
Common mistakes
- Marking
seenon pop instead of on enqueue: lets a room referenced by many neighbors enterqueuedozens of times before its first fetch occurs. - Using recursive DFS: concise on tiny graphs, but raises
RecursionErroron chains deeper than ~1,000 rooms. - Unbounded
while status == 503retry loops: hangs forever if any reachable room never recovers. - Retrying
404or401insiderequest_with_retries: a missing room or rejected Bearer token fails identically on immediate retry; only503is transient here. - Dropping
401URLs 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-tests1 + 2 + ... + K = O(K^2)tokens instead ofO(K).
Alternative approaches
- Deferred
503re-queueing: Instead of firing all 3 attempts back-to-back on the same URL, trackbusy_retries[url]and push a503URL to the back ofqueueup 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
liststack instead ofdeque): Because any reachable exit is accepted, popping from the end of alist(stack.pop()) is equally valid and uses the sameO(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 momentneighborentersseen, withparent[start_url] = None. Once a room opens withis_exit == True, walk backward viacur = parent[cur]untilNoneand 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 viahttpx.AsyncClient) guarded by a semaphore (a concurrency counter such asasyncio.Semaphore(16)capping how many requests can be in flight simultaneously). Workers pull URLs from anasyncio.Queue, shareseen,keys, andlocked, and set anasyncio.Eventas 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 anyRetry-AfterHTTP header returned by the server, apply the same bounded retry policy to429 Too Many Requestsand socket timeouts, and enforce an overall wall-clock deadline on the crawl.
Follow-up questions
- How would you modify the crawler to return the complete sequence of room URLs from start_url to the discovered exit?
- How would you accelerate exploration against a real network service where every HTTP round trip adds tens of milliseconds of latency?
- What backoff, header, and timeout safeguards belong in a production retry policy for 503 responses?
Similar questions
- Identify Recurring Charges in a Card Ledger
- Adaptive-Timeout Web Graph Search with Deferred Retries
- Traveler Airport Lookup by Timestamp
- Versioned Recipe Catalog Service
- Progressive In-Memory Task Manager
- Maximizing Shift Pay with Limited Rest-Day Flips
More Ramp interview questions
- Sliding-Window Request Throttler by Client IP Medium
- Resilient HTTP Graph Crawler with Retries and Cycle Detection Medium
- Adaptive-Timeout Web Graph Search with Deferred Retries Medium Pro
- Shortest Exit Route Through an Unreliable HTTP Maze Medium Pro
- Linear HTTP Endpoint Chain Traversal Medium Pro
- Rolling One-Minute Website Traffic Counter Hard Pro
- Traveler Airport Lookup Across Flight Schedules Medium Pro
- Stateful 3x3 Tic-Tac-Toe Rules Engine Medium Pro
- Versioned Recipe Catalog Service Medium Pro
- Deduplicate and Reconcile Person Records Hard Pro