All Valid Expansions of Wildcard Parentheses
A string contains only (, ) and *. Each * may be replaced by (, by ), or by nothing. A result is valid when its parentheses are balanced: every prefix has at least as many ( as ), and the totals are equal.
Return every distinct valid string that the input can produce, sorted in ascending lexicographic order (( sorts before )). The empty string is a valid result. If none exists, return an empty array.
validExpansions("(**)") -> ["(())", "()", "()()"]
validExpansions("*") -> [""]
validExpansions(")*") -> []The input has at most 16 characters and at most 10 stars. The first part of the round is the yes-or-no check; be ready to give it in O(n) as well.
Hints
Hint 1
Branch on each star three ways and carry the running balance, the number of unmatched ( so far.
Hint 2
Prune early: a negative balance can never recover, and a balance larger than the number of characters left can never be closed.
Hint 3
Different choices can produce the same string, for example ** gives () only one way but the empty string one way too; collect results in a set.
Topics
Asked at
Sign in to use the assistant — ask what the problem means, get a hint when you're stuck, or have your current work reviewed. Conversations save to your account.