Traverse an HTTP Maze

Medium · Coding & Algorithms · Software Engineer · Technical Screen

Problem Statement

An HTTP service exposes a subterranean labyrinth of interconnected chambers, starting at an entrance endpoint such as GET /cavern. Every chamber has a unique string "id", and fetching a chamber returns a JSON payload describing that chamber, any collectible keys inside it, and its outgoing passages:

{
  "id": "S0",
  "message": "entry hall",
  "keys": ["amber"],
  "neighbors": [
    { "direction": "west", "url": "/cavern?location=S1" },
    { "direction": "south", "url": "/cavern?location=S2", "locked": true, "required_key": "amber" }
  ]
}

A chamber is an exit if and only if its "message" field equals "DONE" (exact, case-sensitive match):

{
  "id": "S2",
  "message": "DONE",
  "neighbors": []
}

Implement the labyrinth explorer with the following judge entry point (backed by the same traversal logic you would run against a live HTTP server):

def explore_http_maze(locations: List[Dict], start_id: str) -> Optional[str]:

Your implementation must satisfy these rules:

  • Shallowest-first exploration: Chambers fewer hops away from start_id must be explored before deeper chambers via breadth-first search, returning the "id" of the first "DONE" chamber visited (or None when no exit can be reached).
  • Cycle and broken-link safety: Passages may form cycles or self-loops, omit optional fields ("message", "direction", "keys", "locked"), or point to nonexistent chamber IDs (404). Never loop infinitely, and skip unreachable or malformed entries cleanly.
  • Locked passages and keys: When a neighbor entry specifies "locked": true, it can only be traversed once the key named in "required_key" has been collected from the "keys" list of any visited chamber (including the current chamber). If a key is discovered after its locked passage was first seen, that previously blocked passage becomes traversable and its target chamber must be queued for exploration. ("locked": false or an omitted "locked" field means the passage is open.)
  • Transient HTTP resilience and diagnostics: When backed by a live HTTP transport, retry temporary server failures (500, 502, 503) with backoff and log unexpected responses to aid debugging.

Examples

Example 1

  • Input: python locations = [ { "id": "S0", "neighbors": [ {"direction": "west", "url": "/cavern?location=S1"}, {"direction": "south", "url": "/cavern?location=S2"}, ], }, { "id": "S1", "neighbors": [ {"direction": "east", "url": "/cavern?location=S0"}, {"direction": "west", "url": "/cavern?location=E9"}, ], }, {"id": "S2", "message": "DONE", "neighbors": []}, {"id": "E9", "message": "DONE", "neighbors": []}, ] start_id = "S0"
  • Output: "S2"
  • Explanation: Breadth-first traversal visits "S0" (depth 0), then enqueues "S1" and "S2" (depth 1). Visiting "S1" ignores the back-edge to already-seen "S0" and enqueues "E9" (depth 2), after which "S2" is popped at depth 1 with "message": "DONE" and returned before "E9".

Example 2

  • Input: python locations = [ { "id": "H1", "neighbors": [ {"url": "/cavern?location=EXIT", "locked": True, "required_key": "amber"}, {"url": "/cavern?location=H2"}, ], }, { "id": "H2", "keys": ["amber"], "neighbors": [{"url": "/cavern?location=H1"}], }, {"id": "EXIT", "message": "DONE", "neighbors": []}, ] start_id = "H1"
  • Output: "EXIT"
  • Explanation: At "H1", the passage to "EXIT" requires "amber", so "EXIT" waits while "H2" is explored. Visiting "H2" collects "amber", unlocking the waiting passage to "EXIT", which is then visited and returned.

Constraints

  • 0 <= len(locations) <= 25,000
  • Chamber "id" values and key names are non-empty strings.
  • Each neighbor "url" encodes the destination chamber in its location query parameter (for example, "/cavern?location=S1").
  • Return None if start_id does not exist or if no chamber with "message" == "DONE" is reachable.

Step-by-step walkthrough

  1. Understand the problem and separate exploration from HTTP

    Each chamber in the labyrinth is an HTTP endpoint that returns a JSON object containing the chamber's "id", an optional "message", optional "keys", and a "neighbors" list of outgoing passages (with URLs such as "/cavern?location=S1"). Our goal is to explore outward from the starting node until we visit a chamber whose "message" is exact "DONE", checking shallower chambers before deeper ones, avoiding infinite loops on cycles, logging unexpected responses, retrying transient 5xx errors, and unlocking key-gated passages.

    Because the automated judge runs offline, it passes locations (a list of chamber dictionaries) and start_id to explore_http_maze(locations, start_id). If we write our core graph search against a tiny get(location_id) -> (status_code, body) interface, the exact same search function works both in tests and against a live HTTP server:

                           +--> InMemoryMaze.get(id)   (offline judge tests)
    explore(get, start_id) |
                           +--> HttpMaze.get(id)       (live GET /cavern server)
    
  2. Why breadth-first search (BFS) finds shallow exits and stops cycles

    We must check all chambers 1 hop away before any chamber 2 hops away, and all chambers 2 hops away before 3 hops away. That layer-by-layer order is breadth-first search (BFS), powered by a FIFO (first-in, first-out) queue (collections.deque):

             [S0]             Depth-first (wrong): S0 -> S1 -> E9 (returns depth-2 exit E9!)
            /    \
         [S1]   [S2: DONE]    Breadth-first (right):
          |                     Layer 0: S0
       [E9: DONE]               Layer 1: S1, S2 --> S2 says "DONE" at depth 1!
    

    Labyrinths can also contain cycles (S0 -> S1 -> S0) or diamonds. We keep a seen set of chamber IDs and add each chamber ID at the moment we push it into queue (not later when we pop it). Marking on enqueue guarantees that even if two chambers link to the same destination, that destination is queued and fetched over HTTP only once.

  3. Parse neighbor URLs and build the in-memory server

    Neighbor entries give us a URL string like "/cavern?location=S1" rather than "S1" directly. Slicing strings by fixed offsets breaks if query parameters change order or contain URL-encoded characters (%20), so we use urllib.parse.urlparse and parse_qs to extract "location" safely.

    class InMemoryMaze:
        """In-memory stand-in for the HTTP server used by the automated judge."""
    
        def __init__(self, locations: List[Dict]):
            # by_id: {location_id: response_dict}, e.g. {"S0": {"id": "S0", "neighbors": [...]}}
            self.by_id: Dict[str, Dict] = {}
            for location in locations:
                self.by_id[location["id"]] = location
    
        def get(self, location_id: str) -> Tuple[int, Optional[Dict]]:
            if location_id not in self.by_id:
                return 404, None
            return 200, self.by_id[location_id]
    
    
    def location_id_from_url(url: Any) -> Optional[str]:
        """Extract 'S1' from '/cavern?location=S1', or return None if missing/malformed."""
        if not isinstance(url, str):
            return None
        query_params = parse_qs(urlparse(url).query)
        values = query_params.get("location")
        if not values:
            return None
        return values[0]
    
  4. Fetch rooms with retries, exponential backoff, and diagnostic logging

    Real HTTP servers fail in two very different ways:

    • Transient server errors (500, 502, 503) and network glitches: the server is momentarily overloaded or restarting, so repeating the exact same GET request often succeeds a moment later. We retry up to max_attempts times using exponential backoff — doubling the sleep delay (0.5s, 1.0s, 2.0s, ...) between attempts so we do not overwhelm a recovering server.
    • Permanent errors (404 Not Found, 400, or non-JSON/missing-id payloads): repeating the request will return the same bad response, so we log the chamber ID, HTTP status, and body immediately and return None to skip the broken link.
    # Temporary server error codes where repeating the exact same GET may succeed shortly after.
    TRANSIENT_STATUSES = {500, 502, 503}
    
    
    def fetch_location(
        get,
        location_id: Optional[str],
        max_attempts: int = 3,
        delay_seconds: float = 0.5,
    ) -> Optional[Dict]:
        """GET one room, retrying transient 5xx errors with exponential backoff."""
        for attempt in range(1, max_attempts + 1):
            status, body = get(location_id)
            if status == 200 and isinstance(body, dict) and isinstance(body.get("id"), str):
                return body
    
            # Permanent errors (like 404 or malformed JSON) will not fix themselves on retry.
            if status not in TRANSIENT_STATUSES:
                logger.warning(
                    "GET %s: unexpected response (status=%s, body=%r)",
                    location_id,
                    status,
                    body,
                )
                return None
    
            logger.warning(
                "GET %s: transient status %s on attempt %d/%d (body=%r)",
                location_id,
                status,
                attempt,
                max_attempts,
                body,
            )
            if attempt < max_attempts:
                backoff = delay_seconds * (2 ** (attempt - 1))
                time.sleep(backoff)
    
        logger.warning("GET %s: giving up after %d attempts", location_id, max_attempts)
        return None
    
  5. Key idea for locked passages: park them in a waitlist indexed by key

    As in Example 2, we might encounter an "amber"-locked passage to "EXIT" right at "H1", before we find "keys": ["amber"] over in "H2". If we ignore the locked passage, we never reach "EXIT"; if we re-fetch every chamber from scratch each time we pick up a key, we waste HTTP calls.

    Instead, we maintain two small structures alongside our BFS:

    • collected_keys: the set of key names picked up so far (e.g., {"amber", "silver"}).
    • locked_waitlist: a dictionary mapping required_key -> [target_id, ...] for locked passages whose key we have not found yet.

    Whenever we pick up a new key k, we pop locked_waitlist[k] and push any still-unseen chambers straight onto queue — zero re-fetching!

    Chamber H1 has: locked("amber") -> EXIT, open -> H2 (holds key "amber")
    
    1. Visit H1:   don't have "amber" yet -> park EXIT in locked_waitlist["amber"] = ["EXIT"]; queue H2
    2. Visit H2:   pick up "amber"! Pop locked_waitlist["amber"] -> push "EXIT" onto queue!
    3. Visit EXIT: message == "DONE" -> return "EXIT"
    

    Two subtle ordering rules keep every edge case bug-free:

    1. Collect the current chamber's keys BEFORE inspecting its passages, so if a chamber holds "silver" and also has a "silver"-locked passage, that passage opens right away.
    2. Never add a parked target_id to seen while it is still locked. Another chamber might have an unlocked passage (or a passage locked with a different key we find first) leading to target_id! Leaving target_id out of seen until a valid path actually queues it ensures any open route still reaches it, while checking if unlocked_target not in seen: when unparking prevents queuing it twice later.
  6. Code the BFS explorer and the live HTTP client

    Notice one extra detail when HttpMaze hits GET /cavern at the start: start_id is None because we do not know the entrance's "id" until the first response arrives. Adding seen.add(body["id"]) right after fetching records the entrance's real ID ("S0"), so any cycle pointing back to ?location=S0 knows the entrance was already visited.

    class HttpMaze:
        """Live HTTP client: get(None) requests the entrance; get(id) requests ?location=<id>."""
    
        def __init__(self, entrance_url: str, timeout_seconds: float = 10.0):
            self.entrance_url = entrance_url
            self.timeout_seconds = timeout_seconds
    
        def get(self, location_id: Optional[str]) -> Tuple[int, Any]:
            url = self.entrance_url
            if location_id is not None:
                separator = "&" if "?" in url else "?"
                url = url + separator + urlencode({"location": location_id})
            try:
                with urllib.request.urlopen(url, timeout=self.timeout_seconds) as response:
                    status = response.status
                    text = response.read().decode("utf-8", errors="replace")
            except urllib.error.HTTPError as error:
                return error.code, error.read().decode("utf-8", errors="replace")
            except OSError as error:
                # Treat network timeouts/resets like HTTP 503 so fetch_location retries them.
                return 503, str(error)
    
            try:
                return status, json.loads(text)
            except ValueError:
                # Non-JSON payload on HTTP 200: return raw text so fetch_location logs it cleanly.
                return status, text
    
    
    def explore(get, start_id: Optional[str]) -> Optional[str]:
        """Breadth-first search from start_id; returns the ID of the first 'DONE' room."""
        # seen: IDs already placed in queue, e.g. {"S0", "S1"}, preventing cycles and duplicate fetches
        seen: Set[Optional[str]] = {start_id}
        # queue: FIFO queue of room IDs to fetch in shallow-to-deep order, e.g. deque(["S1", "S2"])
        queue: deque = deque([start_id])
        # collected_keys: key names picked up in visited rooms, e.g. {"amber", "silver"}
        collected_keys: Set[str] = set()
        # locked_waitlist: {required_key: [target_id, ...]} for locked doors seen before their key
        locked_waitlist: Dict[str, List[str]] = {}
    
        while queue:
            location_id = queue.popleft()
            body = fetch_location(get, location_id)
            if body is None:
                continue
    
            # Record body["id"] too because GET /cavern starts with location_id=None.
            room_id = body["id"]
            seen.add(room_id)
    
            raw_neighbors = body.get("neighbors")
            if raw_neighbors is None:
                neighbors = []
            elif isinstance(raw_neighbors, list):
                neighbors = raw_neighbors
            else:
                logger.warning("%s: malformed neighbors field: %r", room_id, raw_neighbors)
                neighbors = []
    
            logger.info(
                "visit %s: message=%r, %d neighbors",
                room_id,
                body.get("message"),
                len(neighbors),
            )
    
            # Phase 1: Stop immediately on an exact "DONE" message ("done" or "DONE " do not count).
            if body.get("message") == "DONE":
                return room_id
    
            # Phase 2: Collect keys BEFORE checking doors so a key in this room unlocks its own doors.
            raw_keys = body.get("keys")
            room_keys = raw_keys if isinstance(raw_keys, list) else []
            for key in room_keys:
                if key in collected_keys:
                    continue
                collected_keys.add(key)
                logger.info("picked up key %r at %s", key, room_id)
                # Release every room that was parked waiting on this newly found key.
                for unlocked_target in locked_waitlist.pop(key, []):
                    if unlocked_target not in seen:
                        seen.add(unlocked_target)
                        queue.append(unlocked_target)
    
            # Phase 3: Inspect outgoing doors; queue open ones and park locked ones by key.
            for neighbor in neighbors:
                if not isinstance(neighbor, dict):
                    logger.warning("%s: malformed neighbor entry: %r", room_id, neighbor)
                    continue
    
                target_id = location_id_from_url(neighbor.get("url"))
                if target_id is None:
                    logger.warning("%s: neighbor missing location param: %r", room_id, neighbor)
                    continue
                if target_id in seen:
                    continue
    
                if neighbor.get("locked"):
                    required_key = neighbor.get("required_key")
                    if required_key not in collected_keys:
                        # Do NOT mark target_id in `seen` yet: another open door (or a door
                        # needing a different key found sooner) may still reach target_id!
                        locked_waitlist.setdefault(required_key, []).append(target_id)
                        continue
    
                seen.add(target_id)
                queue.append(target_id)
    
        return None
    
    
    def explore_http_maze(locations: List[Dict], start_id: str) -> Optional[str]:
        maze = InMemoryMaze(locations)
        return explore(maze.get, start_id)
    
  7. Walk through Example 1

    In Example 1, "S0" connects west to "S1" and south to "S2" ("DONE" at depth 1), while "S1" cycles back to "S0" and leads west to "E9" ("DONE" at depth 2):

    Step | Popped | Action                                        | queue after | seen after
    -----+--------+-----------------------------------------------+-------------+-------------------
    init |   -    | start at S0                                   | [S0]        | {S0}
      1  |   S0   | message=None; enqueue S1 and S2               | [S1, S2]    | {S0, S1, S2}
      2  |   S1   | S0 already in seen (skip cycle); enqueue E9   | [S2, E9]    | {S0, S1, S2, E9}
      3  |   S2   | message=="DONE" -> return "S2" immediately!   | [E9]        | {S0, S1, S2, E9}
    

    Every chamber at depth 1 (S1, S2) is visited before depth 2 (E9), so "S2" wins cleanly without ever fetching "E9" or looping on S1 -> S0.

  8. Complete solution

    from typing import Any, Dict, List, Optional, Set, Tuple
    from collections import deque
    from urllib.parse import parse_qs, urlencode, urlparse
    import json
    import logging
    import sys
    import time
    import urllib.error
    import urllib.request
    
    logger = logging.getLogger("maze")
    
    # Temporary server error codes where repeating the exact same GET may succeed shortly after.
    TRANSIENT_STATUSES = {500, 502, 503}
    
    
    class InMemoryMaze:
        """In-memory stand-in for the HTTP server used by the automated judge."""
    
        def __init__(self, locations: List[Dict]):
            # by_id: {location_id: response_dict}, e.g. {"S0": {"id": "S0", "neighbors": [...]}}
            self.by_id: Dict[str, Dict] = {}
            for location in locations:
                self.by_id[location["id"]] = location
    
        def get(self, location_id: str) -> Tuple[int, Optional[Dict]]:
            if location_id not in self.by_id:
                return 404, None
            return 200, self.by_id[location_id]
    
    
    class HttpMaze:
        """Live HTTP client: get(None) requests the entrance; get(id) requests ?location=<id>."""
    
        def __init__(self, entrance_url: str, timeout_seconds: float = 10.0):
            self.entrance_url = entrance_url
            self.timeout_seconds = timeout_seconds
    
        def get(self, location_id: Optional[str]) -> Tuple[int, Any]:
            url = self.entrance_url
            if location_id is not None:
                separator = "&" if "?" in url else "?"
                url = url + separator + urlencode({"location": location_id})
            try:
                with urllib.request.urlopen(url, timeout=self.timeout_seconds) as response:
                    status = response.status
                    text = response.read().decode("utf-8", errors="replace")
            except urllib.error.HTTPError as error:
                return error.code, error.read().decode("utf-8", errors="replace")
            except OSError as error:
                # Treat network timeouts/resets like HTTP 503 so fetch_location retries them.
                return 503, str(error)
    
            try:
                return status, json.loads(text)
            except ValueError:
                # Non-JSON payload on HTTP 200: return raw text so fetch_location logs it cleanly.
                return status, text
    
    
    def location_id_from_url(url: Any) -> Optional[str]:
        """Extract 'S1' from '/cavern?location=S1', or return None if missing/malformed."""
        if not isinstance(url, str):
            return None
        query_params = parse_qs(urlparse(url).query)
        values = query_params.get("location")
        if not values:
            return None
        return values[0]
    
    
    def fetch_location(
        get,
        location_id: Optional[str],
        max_attempts: int = 3,
        delay_seconds: float = 0.5,
    ) -> Optional[Dict]:
        """GET one room, retrying transient 5xx errors with exponential backoff."""
        for attempt in range(1, max_attempts + 1):
            status, body = get(location_id)
            if status == 200 and isinstance(body, dict) and isinstance(body.get("id"), str):
                return body
    
            # Permanent errors (like 404 or malformed JSON) will not fix themselves on retry.
            if status not in TRANSIENT_STATUSES:
                logger.warning(
                    "GET %s: unexpected response (status=%s, body=%r)",
                    location_id,
                    status,
                    body,
                )
                return None
    
            logger.warning(
                "GET %s: transient status %s on attempt %d/%d (body=%r)",
                location_id,
                status,
                attempt,
                max_attempts,
                body,
            )
            if attempt < max_attempts:
                backoff = delay_seconds * (2 ** (attempt - 1))
                time.sleep(backoff)
    
        logger.warning("GET %s: giving up after %d attempts", location_id, max_attempts)
        return None
    
    
    def explore(get, start_id: Optional[str]) -> Optional[str]:
        """Breadth-first search from start_id; returns the ID of the first 'DONE' room."""
        # seen: IDs already placed in queue, e.g. {"S0", "S1"}, preventing cycles and duplicate fetches
        seen: Set[Optional[str]] = {start_id}
        # queue: FIFO queue of room IDs to fetch in shallow-to-deep order, e.g. deque(["S1", "S2"])
        queue: deque = deque([start_id])
        # collected_keys: key names picked up in visited rooms, e.g. {"amber", "silver"}
        collected_keys: Set[str] = set()
        # locked_waitlist: {required_key: [target_id, ...]} for locked doors seen before their key
        locked_waitlist: Dict[str, List[str]] = {}
    
        while queue:
            location_id = queue.popleft()
            body = fetch_location(get, location_id)
            if body is None:
                continue
    
            # Record body["id"] too because GET /cavern starts with location_id=None.
            room_id = body["id"]
            seen.add(room_id)
    
            raw_neighbors = body.get("neighbors")
            if raw_neighbors is None:
                neighbors = []
            elif isinstance(raw_neighbors, list):
                neighbors = raw_neighbors
            else:
                logger.warning("%s: malformed neighbors field: %r", room_id, raw_neighbors)
                neighbors = []
    
            logger.info(
                "visit %s: message=%r, %d neighbors",
                room_id,
                body.get("message"),
                len(neighbors),
            )
    
            # Phase 1: Stop immediately on an exact "DONE" message ("done" or "DONE " do not count).
            if body.get("message") == "DONE":
                return room_id
    
            # Phase 2: Collect keys BEFORE checking doors so a key in this room unlocks its own doors.
            raw_keys = body.get("keys")
            room_keys = raw_keys if isinstance(raw_keys, list) else []
            for key in room_keys:
                if key in collected_keys:
                    continue
                collected_keys.add(key)
                logger.info("picked up key %r at %s", key, room_id)
                # Release every room that was parked waiting on this newly found key.
                for unlocked_target in locked_waitlist.pop(key, []):
                    if unlocked_target not in seen:
                        seen.add(unlocked_target)
                        queue.append(unlocked_target)
    
            # Phase 3: Inspect outgoing doors; queue open ones and park locked ones by key.
            for neighbor in neighbors:
                if not isinstance(neighbor, dict):
                    logger.warning("%s: malformed neighbor entry: %r", room_id, neighbor)
                    continue
    
                target_id = location_id_from_url(neighbor.get("url"))
                if target_id is None:
                    logger.warning("%s: neighbor missing location param: %r", room_id, neighbor)
                    continue
                if target_id in seen:
                    continue
    
                if neighbor.get("locked"):
                    required_key = neighbor.get("required_key")
                    if required_key not in collected_keys:
                        # Do NOT mark target_id in `seen` yet: another open door (or a door
                        # needing a different key found sooner) may still reach target_id!
                        locked_waitlist.setdefault(required_key, []).append(target_id)
                        continue
    
                seen.add(target_id)
                queue.append(target_id)
    
        return None
    
    
    def explore_http_maze(locations: List[Dict], start_id: str) -> Optional[str]:
        maze = InMemoryMaze(locations)
        return explore(maze.get, start_id)
    
    
    if __name__ == "__main__":
        logging.basicConfig(level=logging.INFO, format="%(levelname)s %(message)s")
        if len(sys.argv) > 1:
            # Live run: python solution.py http://localhost:8000/cavern
            print(explore(HttpMaze(sys.argv[1]).get, None))
        else:
            sample = [
                {
                    "id": "S0",
                    "neighbors": [
                        {"direction": "west", "url": "/cavern?location=S1"},
                        {"direction": "south", "url": "/cavern?location=S2"},
                    ],
                },
                {
                    "id": "S1",
                    "neighbors": [
                        {"direction": "east", "url": "/cavern?location=S0"},
                        {"direction": "west", "url": "/cavern?location=E9"},
                    ],
                },
                {"id": "S2", "message": "DONE", "neighbors": []},
                {"id": "E9", "message": "DONE", "neighbors": []},
            ]
            print(explore_http_maze(sample, "S0"))
    

    ✅ Submit now — all tests should pass.

Intuition & how it works

Imagine exploring an underground network of chambers while carrying a keyring and a notepad, trying to find the nearest exit to the surface. To check nearby chambers before venturing deeper underground, you use breadth-first search (BFS) — a traversal that visits every node at distance 1 before any node at distance 2, and so on, using a FIFO (first-in, first-out) queue where the earliest discovered chamber is always explored next. Whenever you encounter a locked passage whose key you have not collected yet, you jot "amber key -> opens chamber EXIT" on your notepad (locked_waitlist), so the moment you pick up "amber" in another chamber, you immediately push "EXIT" onto your queue without retracing steps or re-requesting old chambers.

A naive recursive or stack-based depth-first search fails here because it plunges down the first branch it sees, potentially returning an exit 50 hops away when another exit sat 1 hop from the start (and looping forever on cycles without a visited set). Likewise, handling keys by restarting the search from start_id after each newly discovered key works, but wastes slow HTTP GET calls re-fetching chambers whose JSON payload never changed.

Trace Example 2 (H1 has an "amber"-locked passage to EXIT and an open passage to H2, while H2 holds "keys": ["amber"]): 1. Start with queue = ["H1"], seen = {"H1"}. Pop and fetch H1: park "EXIT" in locked_waitlist["amber"] (keeping "EXIT" out of seen), and push "H2" onto queue (seen = {"H1", "H2"}). 2. Pop and fetch H2: collect "amber", look up locked_waitlist.pop("amber"), and push "EXIT" onto queue (seen = {"H1", "H2", "EXIT"}). 3. Pop and fetch EXIT: message == "DONE", so we stop immediately and return "EXIT".

Complexity

Let V be the number of reachable chambers, E the total number of neighbor passage entries across those chambers, and K the total number of key entries across those chambers.

  • Time — O(V + E + K) CPU work and at most V chamber fetches (up to max_attempts * V HTTP requests): Every chamber ID enters seen and queue at most once, every outgoing neighbor entry is inspected once when its chamber is fetched (and at most once more if parked in locked_waitlist and later unlocked), and each key entry in room_keys is checked once. Over a real network, total wall-clock time is dominated by the O(V) HTTP round-trips rather than local dictionary/deque work.
  • Space — O(V + E): seen and queue hold at most V chamber IDs, collected_keys holds at most K distinct key names, and locked_waitlist stores at most one target entry per locked passage (<= E). In offline tests, InMemoryMaze also indexes the input list in O(V) space.

Edge cases

  • Starting chamber is already the exit: S0 has "message": "DONE", so explore returns "S0" on the very first pop without fetching any neighbors.
  • Entrance fetched without a query parameter (GET /cavern): start_id begins as None, and seen.add(body["id"]) records the entrance's real ID as soon as it arrives so back-edges to the entrance are never fetched twice.
  • Cycles, self-loops, and no reachable exit: seen prevents any chamber from being queued twice, so queue eventually empties and explore returns None cleanly (including when the exit sits behind a key that does not exist anywhere).
  • Near-miss exit messages ("done", "DONE ", None): Only exact string equality body.get("message") == "DONE" stops the search.
  • Key in the same chamber as its locked passage (or "locked": false): Keys are collected before outgoing passages are checked, and "locked": false treats the passage as open regardless of required_key.
  • Same target behind two locked passages (or one locked passage and one open passage): Because parked targets are not added to seen until queued, whichever key or open path arrives first still queues the chamber.
  • Broken neighbor URLs or 404 responses: Missing location= query parameters and 404 chambers are logged with context and skipped without crashing.

Common mistakes

  • Using depth-first search (recursion or list.pop()): Violates the shallowest-first requirement and hits Python's recursion limit (~1,000 frames) on long corridors.
  • Using list.pop(0) instead of collections.deque.popleft(): Removing index 0 from a Python list shifts every remaining element left in O(V) time per pop instead of O(1).
  • Adding chambers to seen on pop instead of on enqueue: If two rooms both link to S2, checking seen only after popping pushes S2 into queue twice and can send duplicate HTTP requests.
  • Adding locked targets to seen while parking them: Blocks open paths (or passages using a different key) from ever queuing that chamber.
  • Retrying every non-200 status code: Retrying 404 Not Found or 400 Bad Request with backoff wastes seconds on errors that will never recover; only retry transient server/network failures (500, 502, 503, timeouts).
  • Parsing URLs with fragile string slicing (url.split("=")[1]): Breaks when extra query parameters (&shard=1) or URL-encoded characters (%2F) appear.

Alternative approaches

  • Re-scan visited chambers whenever a new key is found: Simpler to think about if you cache already-fetched chamber JSONs in memory (fetched_bodies[id]), though re-scanning all cached chambers on each key takes O(K * (V + E)) work instead of O(V + E + K) with locked_waitlist (and if not cached, wastes up to K * V extra HTTP calls).
  • State-space BFS on (room_id, frozenset_of_keys): Necessary if keys are single-use consumables or if you must physically walk step-by-step rather than calling any discovered URL directly, at the cost of O(V * 2^num_keys) states. Because HTTP allows requesting any discovered URL directly and keys are permanent, our O(V + E + K) waitlist achieves exact reachability exponentially faster.

Follow-up questions

  • How would you reconstruct and return the sequence of directions taken from the starting node to the exit? Record a dictionary parent[target_id] = (room_id, neighbor.get("direction")) at the exact line where target_id is added to seen and queue (storing (room_id, key_source_info) as well if you also need the detour to pick up keys). Once room_id matches "DONE", walk backward from room_id to start_id through parent and reverse the collected list, using O(V) extra space and returning a shortest-hop sequence whenever no locked passages delayed an edge.
  • How could you issue concurrent HTTP requests to reduce wall-clock latency while still guaranteeing shallowest-first exit discovery? Process the BFS level by level: drain all chamber IDs currently in queue (the entire depth-d frontier) and fetch them concurrently via asyncio or concurrent.futures.ThreadPoolExecutor capped by a semaphore (for example, at most 10 in-flight requests). Then iterate through the returned responses in their original frontier order so exit tie-breaking stays deterministic and every depth-d chamber is checked before any depth-(d + 1) request is sent.
  • What safeguards would you add to the HTTP retry policy before running this client against a production service? Add random jitter (multiplying each backoff sleep by a random factor like 0.5 to 1.5 so many clients do not retry at the exact same millisecond), also retry 429 Too Many Requests while respecting any Retry-After response header, and only auto-retry idempotent methods like GET (requests that can be repeated safely without changing server state). In larger systems, wrap the client in a circuit breaker — a guard that fails fast for a short cooldown period if almost every request is timing out — and enforce strict per-request timeouts plus an overall traversal deadline.

Follow-up questions

Similar questions

More Chariot interview questions

All 1 Chariot questions →