Valid Paranthesis Checker

Greedy Algorithms Hard Hard

Find the validity of an input string s that only contains the letters '(', ')' and '*'.


A string entered is legitimate if

  • Any left parenthesis '(' must have a corresponding right parenthesis ')'.
  • Any right parenthesis ')' must have a corresponding left parenthesis '('.
  • Left parenthesis '(' must go before the corresponding right parenthesis ')'.
  • '*' could be treated as a single right parenthesis ')' or a single left parenthesis '(' or an empty string "".

Examples:

Input : s = (*))

Output : true

Explanation : The * can be replaced by an opening '(' bracket. The string after replacing the * mark is "(())" and is a valid string.

Input : s = *(()

Output : false

Explanation : The * replaced with any bracket does not form a valid string.

Input : s = (**()))

Constraints

  • 1 <= s.length <= 104
  • s consist of only '(', ')', '*'.

Hints

  • Use two counters, low and high. low represents the minimum number of unmatched left parentheses. high represents the maximum possible unmatched left parentheses.
  • Ensure that low never drops below 0 during traversal, as that would mean unmatched ) exists. At the end of traversal, check if low == 0, meaning all parentheses can be matched.

Company Tags

Square Electronic Arts Boston Consulting Group Zomato Oracle PayPal Johnson & Johnson Philips Healthcare MongoDB HCL Technologies OYO Rooms HashiCorp Optum GE Healthcare Dropbox Bloomberg Micron Technology Target KPMG Epic Games Robinhood Activision Blizzard NVIDIA Etsy Morgan Stanley Google Microsoft Amazon Meta Apple Netflix Adobe