KatInterview

Wildcard Brackets: Can the Sequence Be Made Valid?

Greedy & IntervalsAuto-graded · 26 test cases
MediumAuto-gradedGreedy & Intervalsgreedystringsparentheses

Last updated

Decide if a string of brackets and wildcards can be made valid by choosing each wildcard's role, testing range-tracking of reachable open counts or a greedy two-pass argument.

You are given a string pattern consisting only of the characters (, ) and *. The * character is a wildcard: you may independently choose to treat each one as an opening bracket (, a closing bracket ), or as nothing at all (it is deleted).

Determine whether some choice of roles for the wildcards produces a valid bracket sequence.

A bracket sequence is valid when both of the following hold:

  • While reading from left to right, the number of ) seen so far never exceeds the number of ( seen so far.
  • At the end, the total number of ( equals the total number of ).

The empty sequence is valid.

Function

def wildcard_valid(pattern: str) -> bool:

Return True if at least one assignment of roles to the wildcards gives a valid sequence, and False otherwise.

Rules

  • Each wildcard is decided separately, so different wildcards may take different roles.
  • Existing ( and ) characters are never changed or moved.
  • A sequence in which the ) count exceeds the ( count at any prefix is invalid, even if the totals are equal at the end.

Constraints

  • 1 <= len(pattern) <= 100
  • Every character of pattern is one of (, ) or *.

Examples

Example 1

Input: wildcard_valid('(*))')

Output: True

Example 2

Input: wildcard_valid(')*(')

Output: False

Example 3

Input: wildcard_valid('*(*')

Output: True

Hints

Hint 1

Trying every role for every wildcard is exponential. Think about what you really need to know after reading a prefix: how many unmatched `(` could be pending.

Hint 2

The set of possible pending-open counts after each prefix is a contiguous range. Track only its smallest and largest values.

Hint 3

A `(` shifts the range up by one, a `)` shifts it down by one, and a `*` widens it by one on each side. Counts below zero are illegal and must be dropped, and if even the largest value goes below zero you can stop with False.