Reachable Vaults and Weighted Bracket Nesting Score
Trees & GraphsAuto-graded · 20 test casesLast updated
Combine graph reachability from a start node with computing a nesting-weighted score of a balanced bracket string, returning both results as a pair.
Write a single function that solves two small independent tasks and returns both answers together.
Part A: Opening every chamber
A building has n chambers numbered 0 through n - 1. Every chamber is locked except chamber 0, which you start in.
The list rooms describes the building: rooms[i] holds the keys lying inside chamber i. A key with value k opens chamber k. Once you pick up a key you keep it forever, and you may return to any chamber you have already opened.
Decide whether you can eventually enter every chamber.
Part B: Scoring a bracket string
You are given a balanced string s made only of '(' and ')'. Its score is defined as follows:
- The string
"()"scores1. - If
AandBare balanced strings, thenscore(A + B) = score(A) + score(B). - If
Ais a balanced string, thenscore("(" + A + ")") = 2 * score(A).
Compute score(s).
Output
Return a list of two elements: [can_open_all, score], where can_open_all is a boolean for Part A and score is the integer for Part B.
Constraints
1 <= n <= 10^4, wheren = len(rooms)0 <= len(rooms[i]) <= 10^4- Every key is an integer in
[0, n - 1]; duplicate keys and keys to the current chamber may appear 1 <= len(s) <= 10^5sis guaranteed to be balanced- The score can be very large; Python integers are unbounded, so return the exact value
Examples
Example 1
Input: open_chambers_and_score_brackets([[1], [2], [3], []], '(()())')
Output: [True, 4]
Example 2
Input: open_chambers_and_score_brackets([[1, 3], [3, 0, 1], [2], [0]], '(()(()))')
Output: [False, 6]
Hints
Hint 1
Treat each chamber as a node and each key as a directed edge to the chamber it opens. The question is then whether every node is reachable from node 0.
Hint 2
Use an explicit stack or queue with a visited array, marking a chamber when you first discover its key. This avoids recursion limits and repeated work.
Hint 3
For the score, only each innermost "()" adds value, and it contributes 2 raised to the number of pairs enclosing it. Track the current depth in one pass.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Part A: reachability
Model the building as a directed graph: chamber i has an edge to chamber k for every key k found in it. Keys are never lost and you can walk back to any opened chamber, so the chambers you can enter are exactly those reachable from chamber 0.
Run an iterative DFS (or BFS) from chamber 0 with a visited array. Mark a chamber as visited when you first find its key and push it onto the stack, so no chamber is pushed twice. At the end, the answer is true if every chamber is visited.
Why it is correct: every visited chamber was reached through a chain of keys starting at chamber 0, so it is truly reachable. Conversely, any chamber reachable by a chain of keys is discovered because each visited chamber is expanded and all its keys are examined. Since holding a key is permanent, the visiting order does not matter.
Part B: bracket score
Expanding the recursive definition shows that only innermost "()" pairs add value. Each enclosing pair doubles what is inside it, and concatenation adds. So the score is the sum, over every innermost "()", of 2^depth, where depth is the number of pairs strictly enclosing it.
Scan the string once, tracking depth. On '(', increase depth. On ')', decrease depth, and if the previous character was '(', this closes an innermost pair, so add 1 << depth (using the depth after decrementing).
This matches the definition by induction: "()" gives 2^0 = 1; for A + B the depths of the pairs are unchanged so the sums add; for "(" + A + ")" every pair in A gains one level of depth, doubling the total.
Complexity
- Part A: time O(n + K) where K is the total number of keys; space O(n).
- Part B: time O(len(s)); extra space O(1) apart from the result (which may be a big integer).
Reference solution
from typing import List
def open_chambers_and_score_brackets(rooms: List[List[int]], s: str) -> List[object]:
n = len(rooms)
visited = [False] * n
visited[0] = True
stack = [0]
while stack:
room = stack.pop()
for key in rooms[room]:
if not visited[key]:
visited[key] = True
stack.append(key)
score = 0
depth = 0
for i, ch in enumerate(s):
if ch == '(':
depth += 1
else:
depth -= 1
if i > 0 and s[i - 1] == '(':
score += 1 << depth
return [all(visited), score]