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
0provides key2; room2provides keys1and4; room1provides key3. Every room0..4is visited, givingTrue. - Parentheses: Inside
"((())())","(())"is2 * 1 = 2and the adjacent"()"adds1for3; the outer pair doubles3to6, and the trailing"()"adds1for6 + 1 = 7.
Example 2
Input: rooms = [[3], [2], [1], [0, 3], [2]], s = "(()((())))"
Output: [False, 10]
- Rooms: Room
0unlocks room3, whose keys[0, 3]unlock nothing new. Rooms1,2, and4remain locked forever, givingFalse. - Parentheses:
"((()))"has value2 * (2 * 1) = 4, so"()((()))"has value1 + 4 = 5, and the outermost pair doubles5to10.
Constraints
1 <= len(rooms) <= 10^40 <= len(rooms[i]) <= 10^4and0 <= rooms[i][j] < len(rooms), with at most10^5total keys across all rooms.2 <= len(s) <= 10^5sconsists solely of'('and')'and is guaranteed to be well-formed (balanced).
Step-by-step walkthrough
Understand the two subproblems
This question combines two independent tasks into one call and returns
[all_visited, total_score]:- Rooms and keys (
rooms): There arenrooms numbered0throughn - 1. Only room0starts unlocked. Entering roomilets you pick up every key inrooms[i]. Keys are reusable, so once you obtain keyk, you can enter roomkwhenever you want. ReturnTrueif allnrooms can be entered starting from room0, orFalseif any room stays locked forever. - Score of parentheses (
s): Given a well-formed string of'('and')', compute its integer score from three rules:"()"has value1.- 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_roomsandscore_of_parentheses—and combine their results at the end.- Rooms and keys (
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
kinside roomidraws an arrowi -> kmeaning "reaching roomialso lets you reach roomk."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 roughlyn^2 / 2steps (5 * 10^7checks forn = 10^4). Instead, we want to inspect each unlocked room's key list exactly once.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):
visitedis a boolean list of lengthntracking which rooms we have already unlocked (visited[0] = Trueat the start).rooms_to_exploreis 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:
- Use a loop stack instead of recursion: A chain of
10,000rooms would make10,000nested recursive calls, crashing Python's default recursion limit of1,000. A plain list stack handles anynsafely. - Mark
visited[key] = Trueas soon as we pushkey: If multiple rooms hold copies of key5, marking5on first discovery ensures room5goes ontorooms_to_exploreonly once andvisited_countcounts 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_roomsPart 2: See how parentheses scores nest and add
Now look at how Example 1's string
"((())())()"gets its score of7by drawing each balanced pair"(" ... ")"as a box:s = " ( ( () ) () ) () " │ ────── ── │ ── │ 2 * 1 1 │ 1 │ └────┬───┘ │ │ │ 2 + 1 = 3 │ │ └───────┬───────┘ │ 2 * 3 = 6 │ └──────┬─────┘ 6 + 1 = 7If we followed the recursive definition literally—scanning
sto find matching outer parentheses and slicing substrings inside—a deeply nested string like"((((...))))"of length10^5would slice and rescan almost the entire string at50,000levels, takingO(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 at0; whenever we see')', we finish the innermost open box, compute its value, and add that value into the box immediately surrounding it.Part 2: Track open groups with a stack of running totals
We keep a stack
frame_scoresholding 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 == "(": push0ontoframe_scoresto begin accumulating the contents of this new'('. - When
ch == ")": popinner_score = frame_scores.pop().- How do we tell rule 1 (
"()"->1) apart from rule 3 ("(" + X + ")"->2 * score(X))? Every non-empty balanced stringXcontains at least one"()", so its score is always>= 1. Therefore,inner_score == 0happens if and only if nothing was inside this pair ("()"), givinggroup_score = 1. Otherwisegroup_score = 2 * inner_score. - Add
group_scoretoframe_scores[-1], which is the enclosing group's running total (rule 2, concatenation).
- How do we tell rule 1 (
When the loop finishes, every
'('has been closed and onlyframe_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]- When
Trace Example 2 end to end
Let's trace both helpers on Example 2:
rooms = [[3], [2], [1], [0, 3], [2]]ands = "(()((())))".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] = 10Combining both parts returns
[False, 10], matching Example 2.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:
- Exploring locked rooms: Picture a building where room
0starts 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). - Scoring nested parentheses: Picture nested gift boxes. An empty box
"()"contains a1-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
visitedlist of lengthninO(n)time, push and pop each reachable room at most once, and loop through each reachable room's key list once, inspecting at mostKkeys in total. - Rooms space — O(n): Both the
visitedboolean list and therooms_to_explorestack hold at mostnentries 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
mcharacters ofsonce, performing oneO(1)push or pop per character. With fixed-width integers this isO(m)time; in Python, a maximally nested string ofm / 2pairs has score2^(m/2 - 1)(an integer with ~m / 2bits), so doubling multi-thousand-bit integers takes time proportional to their bit length, thoughm = 10^5still finishes in a few hundredths of a second. - Parentheses space — O(d), which is O(m) in the worst case: The
frame_scoresstack stores one integer per currently open'('plus one root slot, so its maximum height isd + 1whered <= m / 2is the deepest nesting level.
Edge cases
- Single room (
rooms = [[]]): Room0starts unlocked, sovisited_countis already1 == total_roomsand the answer isTrueregardless of keys. - Room
0has no keys withn > 1(rooms = [[], [0]]):rooms_to_exploreempties immediately withvisited_count = 1 < n, returningFalse. - Self-keys and duplicate keys (
rooms = [[0, 1, 1], []]): Thenot visited[key]check ignores keys to room0and second copies of key1, preventing double-counting. - Keys trapped in an unreachable cycle (
rooms = [[3], [2], [1], [0, 3], [2]]): Rooms1and2unlock each other, but neither is reachable from{0, 3}, so the search rightly returnsFalse. - Long linear chain (
0 -> 1 -> ... -> 9999): Handled cleanly without hittingRecursionErrorbecauserooms_to_exploreis an explicit list on the heap. - Extremes of parentheses structure: Minimal
"()"scores1, flat"()" * 50000adds1fifty thousand times to50000, and deep"(" * 50000 + ")" * 50000computes2^49999exactly using Python's arbitrary-precision integers.
Common mistakes
- Using recursive DFS in Python: A valid graph algorithm in theory, but
n = 10^4rooms arranged in a chain exceeds Python's default1,000-frame call-stack limit. - Marking a room visited on
pop()instead of onappend(): If100rooms all contain key5and you wait until5is popped to mark it visited,5gets pushed onto the stack100times—and if you incrementvisited_counton push without marking, duplicate keys inflatevisited_counttoneven when rooms remain locked! - Scoring
"()"as2 * 0 = 0: Forgetting the base case wheninner_score == 0makes every"()"worth0, causing the entire string to score0. - Trying to compute the score from total pairs or max depth alone:
"(())()"(2 + 1 = 3) and"((()))"(4) both have3pairs, while"((())())"(6) and"((()))"(4) both have max depth3. 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 sameO(n + K)time andO(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 insidedsurrounding pairs contributes2^dto the final score. Using a bit shift (1 << d, which shifts the binary bit1left bydplaces to compute2^d), we only need an integerdepthcounter 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]isFalsefor every unreachable roomr. Scanningrange(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 oneO(n)pass without sorting. - Can you compute the parentheses score using O(1) extra space beyond the output integer? Yes—track an integer
depththat increments on'('and decrements on')'. Whenevers[i] == ')'immediately followss[i - 1] == '(', you have just closed an innermost"()"enclosed bydepthouter pairs, so you add1 << depthdirectly 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
chis neither'('nor')', or if')'arrives whenlen(frame_scores) == 1(meaning no matching'('is open), raise aValueErrorimmediately. Once the loop ends, also check thatlen(frame_scores) == 1to catch any unclosed'('characters.
Follow-up questions
- How would you return the sorted list of unreachable room IDs instead of a boolean?
- Can you compute the parentheses score using O(1) extra space beyond the output integer?
- How would you adapt the parentheses scorer if the input string might be unbalanced or contain invalid characters?
Similar questions
- Maximum-Dominated Subarray Spans
- Range Sum Queries with Point Updates
- Design Search Autocomplete
- Daily Top Spenders and Post-Launch Cost per KPI
- 2D Max Pooling with Source Coordinates
- Time-Limited Credit Ledger