KatInterview

Reachable Vaults and Weighted Bracket Nesting Score

Trees & GraphsAuto-graded · 20 test cases
MediumAuto-gradedTrees & Graphsgraph-traversaldfsstrings

Last 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:

  1. The string "()" scores 1.
  2. If A and B are balanced strings, then score(A + B) = score(A) + score(B).
  3. If A is a balanced string, then score("(" + 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, where n = 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^5
  • s is 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.