Room Key Reachability and Balanced Parentheses Score

Medium · Coding & Algorithms · Software Engineer · Technical Screen

Problem Statement

Implement visit_rooms_and_score_parentheses(rooms, s) to solve two independent algorithmic tasks and return their answers together as a two-element list [can_open_all, paren_score].

Part 1 — Room reachability (rooms -> can_open_all): - A facility contains n = len(rooms) rooms numbered 0 through n - 1. At the start, room 0 is unlocked and rooms 1 through n - 1 are locked. - Whenever you enter room i, you collect every key listed in rooms[i]. Each key k opens room k and can be reused indefinitely (rooms[i] may contain duplicate keys or keys to already-open rooms). - Set can_open_all to True if you can eventually enter all n rooms starting from room 0, or False if any room stays unreachable.

Part 2 — Nested parentheses valuation (s -> paren_score): - Given a non-empty, well-formed string s made up exclusively of '(' and ')', compute its integer value paren_score according to three rules: 1. An empty pair "()" evaluates to 1. 2. Placing two well-formed strings X and Y next to each other adds their values: score(X + Y) = score(X) + score(Y). 3. Wrapping a non-empty well-formed string X inside an outer pair "(" + X + ")" doubles its value: score("(" + X + ")") = 2 * score(X).

Examples

Example 1

Input: rooms = [[2], [3], [1, 4], [], [0]], s = "((())())()"
Output: [True, 7]
  • Rooms: Room 0 provides key 2; room 2 provides keys 1 and 4; room 1 provides key 3. Every room 0..4 is visited, giving True.
  • Parentheses: Inside "((())())", "(())" is 2 * 1 = 2 and the adjacent "()" adds 1 for 3; the outer pair doubles 3 to 6, and the trailing "()" adds 1 for 6 + 1 = 7.

Example 2

Input: rooms = [[3], [2], [1], [0, 3], [2]], s = "(()((())))"
Output: [False, 10]
  • Rooms: Room 0 unlocks room 3, whose keys [0, 3] unlock nothing new. Rooms 1, 2, and 4 remain locked forever, giving False.
  • Parentheses: "((()))" has value 2 * (2 * 1) = 4, so "()((()))" has value 1 + 4 = 5, and the outermost pair doubles 5 to 10.

Constraints

  • 1 <= len(rooms) <= 10^4
  • 0 <= len(rooms[i]) <= 10^4 and 0 <= rooms[i][j] < len(rooms), with at most 10^5 total keys across all rooms.
  • 2 <= len(s) <= 10^5
  • s consists solely of '(' and ')' and is guaranteed to be well-formed (balanced).

Step-by-step walkthrough

  1. Understand the two subproblems

    This question combines two independent tasks into one call and returns [all_visited, total_score]:

    1. Rooms and keys (rooms): There are n rooms numbered 0 through n - 1. Only room 0 starts unlocked. Entering room i lets you pick up every key in rooms[i]. Keys are reusable, so once you obtain key k, you can enter room k whenever you want. Return True if all n rooms can be entered starting from room 0, or False if any room stays locked forever.
    2. Score of parentheses (s): Given a well-formed string of '(' and ')', compute its integer score from three rules:
      • "()" has value 1.
      • Adjacent balanced strings add: score(X + Y) = score(X) + score(Y).
      • Wrapping a non-empty balanced string inside "(" + X + ")" doubles its value: 2 * score(X).

    We will write one clean helper function for each part—can_visit_all_rooms and score_of_parentheses—and combine their results at the end.

  2. Part 1: Model rooms and keys as a directed graph

    Because keys are never consumed, the order in which you step into unlocked rooms never locks you out of another option. You only gain access to more and more rooms.

    We can picture this as a directed graph (a network of nodes linked by one-way arrows): each room is a node, and finding key k inside room i draws an arrow i -> k meaning "reaching room i also lets you reach room k."

    Compare Example 1 and Example 2 with arrows:

    Example 1: rooms = [[2], [3], [1, 4], [], [0]]
      0 ──> 2 ──> 1 ──> 3          All 5 rooms {0, 1, 2, 3, 4} are reachable -> True
      ^     │
      └──── 4 <──┘
    
    Example 2: rooms = [[3], [2], [1], [0, 3], [2]]
      0 <──> 3 ──┐   4 ──> 2 <──> 1    From 0 we only ever reach {0, 3};
             ^   │                     rooms {1, 2, 4} have no incoming arrow from {0, 3} -> False
             └───┘
    

    A naive idea is to repeatedly loop over every unlocked room and add newly found keys until a full pass adds nothing new. On a chain 0 -> 1 -> 2 -> ... -> n - 1, each pass unlocks just one new room while re-reading all previously unlocked rooms, costing roughly n^2 / 2 steps (5 * 10^7 checks for n = 10^4). Instead, we want to inspect each unlocked room's key list exactly once.

  3. Part 1: Explore reachable rooms with an explicit stack

    To inspect each reachable room once, we run a depth-first search (DFS) (a graph traversal that keeps a to-do pile of newly discovered nodes and explores one at a time until the pile is empty):

    • visited is a boolean list of length n tracking which rooms we have already unlocked (visited[0] = True at the start).
    • rooms_to_explore is a Python list acting as a stack (a last-in, first-out pile where .append() pushes and .pop() removes the top item). It holds unlocked rooms whose key lists we have not yet inspected.

    Two implementation details matter here:

    1. Use a loop stack instead of recursion: A chain of 10,000 rooms would make 10,000 nested recursive calls, crashing Python's default recursion limit of 1,000. A plain list stack handles any n safely.
    2. Mark visited[key] = True as soon as we push key: If multiple rooms hold copies of key 5, marking 5 on first discovery ensures room 5 goes onto rooms_to_explore only once and visited_count counts distinct rooms rather than duplicate keys.
    def can_visit_all_rooms(rooms: List[List[int]]) -> bool:
        """Return True if every room is reachable from room 0 by collecting keys."""
        total_rooms = len(rooms)
        if total_rooms == 0:
            return True
    
        # visited[r] is True once we have unlocked room r (room 0 starts unlocked).
        visited = [False] * total_rooms
        visited[0] = True
        visited_count = 1
    
        # rooms_to_explore: stack of unlocked room indices whose key lists we have
        # not inspected yet, e.g. [0, 3, 1]. Using a list avoids recursion limits.
        rooms_to_explore = [0]
    
        while rooms_to_explore:
            current_room = rooms_to_explore.pop()
            for key in rooms[current_room]:
                # Mark visited right when pushing so duplicate keys never push
                # the same room onto the stack more than once.
                if not visited[key]:
                    visited[key] = True
                    visited_count += 1
                    rooms_to_explore.append(key)
    
        return visited_count == total_rooms
    
  4. Part 2: See how parentheses scores nest and add

    Now look at how Example 1's string "((())())()" gets its score of 7 by drawing each balanced pair "(" ... ")" as a box:

    s = " (  ( () )   ()  )    () "
          │  ──────   ──  │    ──
          │  2 * 1    1   │    1
          │  └────┬───┘   │    │
          │   2 + 1 = 3   │    │
          └───────┬───────┘    │
              2 * 3 = 6        │
                  └──────┬─────┘
                     6 + 1 = 7
    

    If we followed the recursive definition literally—scanning s to find matching outer parentheses and slicing substrings inside—a deeply nested string like "((((...))))" of length 10^5 would slice and rescan almost the entire string at 50,000 levels, taking O(m^2) time and overflowing Python's recursion limit.

    Notice what happens as we read left to right instead: whenever we see '(', we step inside a brand-new box whose inner total starts at 0; whenever we see ')', we finish the innermost open box, compute its value, and add that value into the box immediately surrounding it.

  5. Part 2: Track open groups with a stack of running totals

    We keep a stack frame_scores holding one running integer total per currently open group, starting with [0] at the bottom to collect the top-level score of the whole string:

    • When ch == "(": push 0 onto frame_scores to begin accumulating the contents of this new '('.
    • When ch == ")": pop inner_score = frame_scores.pop().
      • How do we tell rule 1 ("()" -> 1) apart from rule 3 ("(" + X + ")" -> 2 * score(X))? Every non-empty balanced string X contains at least one "()", so its score is always >= 1. Therefore, inner_score == 0 happens if and only if nothing was inside this pair ("()"), giving group_score = 1. Otherwise group_score = 2 * inner_score.
      • Add group_score to frame_scores[-1], which is the enclosing group's running total (rule 2, concatenation).

    When the loop finishes, every '(' has been closed and only frame_scores[0] remains—our final answer.

    def score_of_parentheses(s: str) -> int:
        """Return the score of a balanced parentheses string."""
        # frame_scores: stack of running totals for currently open '(' groups,
        # e.g. [0, 1, 0]. frame_scores[0] collects the top-level total score.
        frame_scores = [0]
    
        for ch in s:
            if ch == "(":
                # A new '(' opens an inner group whose running total starts at 0.
                frame_scores.append(0)
            else:
                # A ')' closes the innermost open group.
                inner_score = frame_scores.pop()
    
                # Every non-empty balanced inner string scores at least 1, so
                # inner_score == 0 happens if and only if this pair was just "()".
                if inner_score == 0:
                    group_score = 1
                else:
                    group_score = 2 * inner_score
    
                # Side-by-side groups add together inside their enclosing group.
                frame_scores[-1] += group_score
    
        return frame_scores[0]
    
  6. Trace Example 2 end to end

    Let's trace both helpers on Example 2: rooms = [[3], [2], [1], [0, 3], [2]] and s = "(()((())))".

    Part 1 trace: rooms = [[3], [2], [1], [0, 3], [2]]
      Start:  visited = [T, F, F, F, F], visited_count = 1, rooms_to_explore = [0]
      Pop 0:  key 3 is new -> mark 3
              visited = [T, F, F, T, F], visited_count = 2, rooms_to_explore = [3]
      Pop 3:  keys [0, 3] -> both already visited
              visited = [T, F, F, T, F], visited_count = 2, rooms_to_explore = []
      Done:   visited_count (2) == total_rooms (5) is False!
    
    Part 2 trace: s = "(()((())))"
      Start:                   frame_scores = [0]
      ch = '(' -> push 0       frame_scores = [0, 0]
      ch = '(' -> push 0       frame_scores = [0, 0, 0]
      ch = ')' -> pop 0 -> +1  frame_scores = [0, 1]
      ch = '(' -> push 0       frame_scores = [0, 1, 0]
      ch = '(' -> push 0       frame_scores = [0, 1, 0, 0]
      ch = '(' -> push 0       frame_scores = [0, 1, 0, 0, 0]
      ch = ')' -> pop 0 -> +1  frame_scores = [0, 1, 0, 1]
      ch = ')' -> pop 1 -> +2  frame_scores = [0, 1, 2]
      ch = ')' -> pop 2 -> +4  frame_scores = [0, 5]
      ch = ')' -> pop 5 -> +10 frame_scores = [10]
      Done:   frame_scores[0] = 10
    

    Combining both parts returns [False, 10], matching Example 2.

  7. Complete solution

    from typing import Any, Dict, List, Optional, Set, Tuple
    
    
    def can_visit_all_rooms(rooms: List[List[int]]) -> bool:
        """Return True if every room is reachable from room 0 by collecting keys."""
        total_rooms = len(rooms)
        if total_rooms == 0:
            return True
    
        # visited[r] is True once we have unlocked room r (room 0 starts unlocked).
        visited = [False] * total_rooms
        visited[0] = True
        visited_count = 1
    
        # rooms_to_explore: stack of unlocked room indices whose key lists we have
        # not inspected yet, e.g. [0, 3, 1]. Using a list avoids recursion limits.
        rooms_to_explore = [0]
    
        while rooms_to_explore:
            current_room = rooms_to_explore.pop()
            for key in rooms[current_room]:
                # Mark visited right when pushing so duplicate keys never push
                # the same room onto the stack more than once.
                if not visited[key]:
                    visited[key] = True
                    visited_count += 1
                    rooms_to_explore.append(key)
    
        return visited_count == total_rooms
    
    
    def score_of_parentheses(s: str) -> int:
        """Return the score of a balanced parentheses string."""
        # frame_scores: stack of running totals for currently open '(' groups,
        # e.g. [0, 1, 0]. frame_scores[0] collects the top-level total score.
        frame_scores = [0]
    
        for ch in s:
            if ch == "(":
                # A new '(' opens an inner group whose running total starts at 0.
                frame_scores.append(0)
            else:
                # A ')' closes the innermost open group.
                inner_score = frame_scores.pop()
    
                # Every non-empty balanced inner string scores at least 1, so
                # inner_score == 0 happens if and only if this pair was just "()".
                if inner_score == 0:
                    group_score = 1
                else:
                    group_score = 2 * inner_score
    
                # Side-by-side groups add together inside their enclosing group.
                frame_scores[-1] += group_score
    
        return frame_scores[0]
    
    
    def visit_rooms_and_score_parentheses(rooms: List[List[int]], s: str) -> List[object]:
        all_visited = can_visit_all_rooms(rooms)
        total_score = score_of_parentheses(s)
        return [all_visited, total_score]
    

    ✅ Submit now — all tests should pass.

Intuition & how it works

Imagine solving two everyday puzzles one after the other:

  1. Exploring locked rooms: Picture a building where room 0 starts unlocked and every room has a bowl of reusable master keys on a table. Because using a key never uses it up, the order in which you open doors cannot trap you—you simply keep a checklist of unlocked rooms and a stack (a last-in, first-out to-do pile) of unlocked rooms whose key bowls you have not checked yet. This graph traversal is called depth-first search (DFS) (exploring reachable nodes one by one using a stack until no unvisited neighbors remain).
  2. Scoring nested parentheses: Picture nested gift boxes. An empty box "()" contains a 1-point coin, boxes placed side by side add their points together, and sealing boxes inside an outer box doubles whatever points are inside. By keeping a stack of running totals—one slot for each currently open '(' box—we tally each box the moment its closing ')' arrives and add its points into the surrounding box.

Why do the naive approaches fall short? For the rooms puzzle, repeatedly scanning all unlocked rooms in rounds re-reads old key bowls up to n times on a hallway 0 -> 1 -> ... -> n - 1 (O(n * K) work), while recursive DFS crashes Python's recursion limit (the maximum number of nested function calls Python allows on the call stack, about 1,000 by default) when n = 10,000. For the parentheses puzzle, recursively slicing "(" + inside + ")" substrings re-scans the inner characters at every nesting level (O(m^2) work on "((((...))))") and hits the same recursion limit.

Walk through Example 1 with rooms = [[2], [3], [1, 4], [], [0]] and s = "((())())()": - Rooms: Start with visited = [T, F, F, F, F] and rooms_to_explore = [0]. Pop 0 and push 2; pop 2 and push 1 and 4; pop 4 (key 0 is already visited); pop 1 and push 3; pop 3 (no keys). All 5 of 5 rooms are visited, giving True. - Parentheses: Start with frame_scores = [0]. Three '(' characters build [0, 0, 0, 0]; ')' pops 0 -> +1 ([0, 0, 1]); ')' pops 1 -> +2 ([0, 2]); '(' and ')' add 1 ([0, 3]); ')' pops 3 -> +6 ([6]); and the final "()" adds 1 ([7]). Returning both answers yields [True, 7].

Complexity

Let n be the number of rooms, K be the total number of keys across all rooms, and m be the length of s.

  • Rooms time — O(n + K): We initialize the visited list of length n in O(n) time, push and pop each reachable room at most once, and loop through each reachable room's key list once, inspecting at most K keys in total.
  • Rooms space — O(n): Both the visited boolean list and the rooms_to_explore stack hold at most n entries because a room is marked visited before it is pushed.
  • Parentheses time — O(m) stack steps (up to O(m^2) bit operations for huge answers): We scan the m characters of s once, performing one O(1) push or pop per character. With fixed-width integers this is O(m) time; in Python, a maximally nested string of m / 2 pairs has score 2^(m/2 - 1) (an integer with ~m / 2 bits), so doubling multi-thousand-bit integers takes time proportional to their bit length, though m = 10^5 still finishes in a few hundredths of a second.
  • Parentheses space — O(d), which is O(m) in the worst case: The frame_scores stack stores one integer per currently open '(' plus one root slot, so its maximum height is d + 1 where d <= m / 2 is the deepest nesting level.

Edge cases

  • Single room (rooms = [[]]): Room 0 starts unlocked, so visited_count is already 1 == total_rooms and the answer is True regardless of keys.
  • Room 0 has no keys with n > 1 (rooms = [[], [0]]): rooms_to_explore empties immediately with visited_count = 1 < n, returning False.
  • Self-keys and duplicate keys (rooms = [[0, 1, 1], []]): The not visited[key] check ignores keys to room 0 and second copies of key 1, preventing double-counting.
  • Keys trapped in an unreachable cycle (rooms = [[3], [2], [1], [0, 3], [2]]): Rooms 1 and 2 unlock each other, but neither is reachable from {0, 3}, so the search rightly returns False.
  • Long linear chain (0 -> 1 -> ... -> 9999): Handled cleanly without hitting RecursionError because rooms_to_explore is an explicit list on the heap.
  • Extremes of parentheses structure: Minimal "()" scores 1, flat "()" * 50000 adds 1 fifty thousand times to 50000, and deep "(" * 50000 + ")" * 50000 computes 2^49999 exactly using Python's arbitrary-precision integers.

Common mistakes

  • Using recursive DFS in Python: A valid graph algorithm in theory, but n = 10^4 rooms arranged in a chain exceeds Python's default 1,000-frame call-stack limit.
  • Marking a room visited on pop() instead of on append(): If 100 rooms all contain key 5 and you wait until 5 is popped to mark it visited, 5 gets pushed onto the stack 100 times—and if you increment visited_count on push without marking, duplicate keys inflate visited_count to n even when rooms remain locked!
  • Scoring "()" as 2 * 0 = 0: Forgetting the base case when inner_score == 0 makes every "()" worth 0, causing the entire string to score 0.
  • Trying to compute the score from total pairs or max depth alone: "(())()" (2 + 1 = 3) and "((()))" (4) both have 3 pairs, while "((())())" (6) and "((()))" (4) both have max depth 3. Every innermost "()" contributes independently according to its own depth.

Alternative approaches

  • Breadth-first search (BFS) for rooms: A breadth-first search (BFS) (a traversal that explores nodes in first-in, first-out order using a queue such as collections.deque) visits rooms wave by wave instead of deep-first, reaching the exact same set of rooms in the same O(n + K) time and O(n) space.
  • Leaf-depth counting for parentheses (O(1) auxiliary space): Because multiplication distributes over addition (2 * (a + b) = 2*a + 2*b), every innermost "()" sitting inside d surrounding pairs contributes 2^d to the final score. Using a bit shift (1 << d, which shifts the binary bit 1 left by d places to compute 2^d), we only need an integer depth counter instead of a stack:
def score_by_depth(s: str) -> int:
    score = 0
    depth = 0
    for i, ch in enumerate(s):
        if ch == "(":
            depth += 1
        else:
            depth -= 1
            if s[i - 1] == "(":
                # An innermost "()" enclosed by `depth` outer pairs adds 2^depth.
                score += 1 << depth
    return score

Follow-up questions

  • How would you return the sorted list of unreachable room IDs instead of a boolean? After the while rooms_to_explore: loop finishes, visited[r] is False for every unreachable room r. Scanning range(total_rooms) in ascending order ([r for r in range(total_rooms) if not visited[r]]) directly produces the sorted list of locked room IDs in one O(n) pass without sorting.
  • Can you compute the parentheses score using O(1) extra space beyond the output integer? Yes—track an integer depth that increments on '(' and decrements on ')'. Whenever s[i] == ')' immediately follows s[i - 1] == '(', you have just closed an innermost "()" enclosed by depth outer pairs, so you add 1 << depth directly to the running score.
  • How would you adapt the parentheses scorer if the input string might be unbalanced or contain invalid characters? Validate during the single scan: if ch is neither '(' nor ')', or if ')' arrives when len(frame_scores) == 1 (meaning no matching '(' is open), raise a ValueError immediately. Once the loop ends, also check that len(frame_scores) == 1 to catch any unclosed '(' characters.

Follow-up questions

Similar questions

More Moloco interview questions

All 5 Moloco questions →