Skip to main content

Valid Parenthesis String

Medium
Data Structures and Algorithms
Editorial
Topics:
Greedy
Stack
String

Given a string s, determine whether it can represent a correctly balanced sequence of parentheses. The string contains opening parentheses (, closing parentheses ), and wildcard characters *.

Each * may be interpreted as a single (, a single ), or an empty character. All non-wildcard characters retain their original meaning, and each wildcard receives exactly one of these interpretations.

Return true if some interpretation of every * produces a valid parenthesis sequence, and return false otherwise. A valid sequence has matching pairs in the proper order, with no closing parenthesis appearing before its matching opening parenthesis.

Example 1:

Input: s = "(*()"
Output: true
Explanation: Interpret * as ), producing (()), which is balanced.

Example 2:

Input: s = "())*"
Output: false
Explanation: The first three characters already leave one unmatched closing parenthesis, and the final wildcard cannot repair that ordering.

Example 3:

Input: s = "***"
Output: true
Explanation: For instance, interpret the three wildcards as (, ), and an empty character to obtain ().

Constraints:

  • 1 <= s.length <= 10^5
  • Each character in sis(, ), or *.
  • Each * represents at most one character in the interpreted sequence.
  • The input string is provided as a JSON string.

Need help or want more practice?

Practise in an interviewGet AI Coach help