Library Nesting Tab Fees

Minimum assignment cost for a balanced sequence with fixed symbols

HardGreedyHeapPrefix Balance

A library packs archival documents into nested protective sleeves. Its packing tape records sleeve actions from left to right:

  • ( opens a sleeve.
  • ) closes the most recently opened sleeve that is still open.
  • ? is a flexible tab that must be assigned either action.

A valid tape never closes a sleeve when none is open, and every opened sleeve is closed by the end.

The array fees lists the flexible tabs' fees in their left-to-right order. Assigning the corresponding tab to ( costs that fee; assigning it to ) is free. Existing parentheses cannot be changed.

Return the minimum total fee needed to make the tape valid. Return -1 if no valid assignment exists. An empty tape is valid and costs zero.

Examples

Example 1

Input: tape = "?()?", fees = [7,2]
Output: 7

The first flexible tab must open a sleeve and the last must close one. The fixed middle actions already form a complete nested unit.

Example 2

Input: tape = "??()??", fees = [9,1,4,2]
Output: 10

Opening both of the first two flexible tabs lets the fixed opening action sit inside them. The two trailing flexible tabs can then close sleeves. Opening the cheaper second tab avoids paying to open a later tab.

Example 3

Input: tape = ")?", fees = [3]
Output: -1

The first action closes a sleeve before any sleeve has opened. No assignment to a later tab can repair that prefix.

Constraints

  • 0 <= len(tape) <= 100000
  • Every character of tape is '(', ')', or '?'.
  • len(fees) equals the number of '?' characters in tape.
  • 0 <= fees[i] <= 1000000000

The running balance is the number of opening actions minus closing actions. A valid tape has nonnegative balance at every prefix and final balance zero. A reference implementation uses O(n log(q + 1)) time and O(q) space, where q is the number of flexible tabs. Total fees fit in an exact JavaScript Number.

Hints

Show hint 1

Initially regard every flexible tab as a closing action. What change repairs a prefix whose balance becomes negative?

Show hint 2

When a repair is necessary, choose the cheapest flexible tab in the prefix that has not already been assigned as an opening action.

Follow-up questions

What an interviewer might ask once you have a working solution.

  • How would you also return one minimum-cost completed tape?
  • How would the algorithm change if each flexible tab had separate opening and closing fees?

Practice this with an AI interviewer

Explain your approach out loud, write Python or JavaScript, run it against hidden tests (including large inputs), and get a scored debrief.

Start this problem