Taro Logo

Valid Parenthesis String

#2 Most AskedMedium
2 views
Topics:
ArraysTwo PointersGreedy Algorithms

Given a string s containing only three types of characters: '(', ')' and '*', return true if s is valid.

The following rules define a valid string:

  • 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 "".

Example 1:

Input: s = "()"
Output: true

Example 2:

Input: s = "(*)"
Output: true

Example 3:

Input: s = "(*))"
Output: true

Constraints:

  • 1 <= s.length <= 100
  • s[i] is '(', ')' or '*'.

Solution


Clarifying Questions

When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:

  1. What is the maximum length of the input string, and should we expect any memory or performance constraints?
  2. How should we handle an empty string or a string consisting entirely of asterisks—do they evaluate to valid?
  3. Can the asterisk ('*') evaluate to different characters independently throughout the string, such as acting as '(' in one place and ')' in another?
  4. Are there any characters other than '(', ')', and '*' that could possibly be present in the input string, or can we assume the input is strictly well-formed in terms of allowed characters?
  5. Is the return type strictly a boolean, or should we be concerned with returning any additional metadata or error states?

Brute Force Solution

Approach

Imagine you have a puzzle containing standard opening and closing parentheses, along with wildcards that can pretend to be either one or nothing at all. The brute force strategy involves testing every single possible identity for every wildcard to see if any combination creates a perfectly balanced set of parentheses.

Here's how the algorithm would work step-by-step:

  1. Look at the very first character of the puzzle.
  2. If it is a wildcard, split your path into three separate future scenarios: pretend the wildcard is an opening parenthesis, pretend it is a closing parenthesis, and pretend it is completely blank.
  3. Follow each of these new paths forward, doing the exact same thing whenever you encounter another wildcard.
  4. Keep track of how many opening parentheses are currently waiting for a match along each path.
  5. If a closing parenthesis appears when no opening parenthesis is waiting, that specific path has failed, so stop following it.
  6. If a path manages to reach the very end of the puzzle and every single opening parenthesis has been successfully matched, declare success because a valid combination has been found.
  7. If you try every single possibility and none of them work out, conclude that the puzzle cannot be solved.

Code Implementation

class Solution:
    def checkValidString(self, input_string: str) -> bool:
        
        def evaluate_paths(string_index, open_count):
            # Fail early if closing brackets exceed available opening brackets to prune invalid paths
            if open_count < 0:
                return False
                
            if string_index == len(input_string):
                return open_count == 0
                
            current_char = input_string[string_index]
            
            if current_char == '(':
                return evaluate_paths(string_index + 1, open_count + 1)
            elif current_char == ')':
                return evaluate_paths(string_index + 1, open_count - 1)
            else:
                # Branch into three possibilities for the wildcard to explore all valid combinations
                return (
                    evaluate_paths(string_index + 1, open_count + 1) or 
                    evaluate_paths(string_index + 1, open_count - 1) or 
                    evaluate_paths(string_index + 1, open_count)
                )
                
        return evaluate_paths(0, 0)

Big(O) Analysis

Time Complexity
O(3^n) – For each character in the input string of size n, if it is a wildcard, the algorithm branches into three separate recursive paths: treating it as an opening parenthesis, a closing parenthesis, or an empty string. This exponential branching repeats for every wildcard encountered across the length of the string. In the worst-case scenario where every character is a wildcard, this creates a recursion tree with a branching factor of 3 and a depth of n. This leads to approximately 3 to the power of n operations, which simplifies to O(3^n).
Space Complexity
O(n) – The brute force strategy described in the plain English explanation involves branching into multiple future scenarios whenever a wildcard is encountered, resulting in a recursive depth proportional to the input size N. Each recursive call adds a new stack frame to the call stack as it tracks the state of the parentheses and wildcards. Because the recursion tree can go as deep as the length of the string N, the maximum auxiliary memory consumed by the recursion stack frames is directly proportional to N. Therefore, the total extra memory required simplifies in Big O notation to O(n).

Optimal Solution

Approach

Instead of guessing every possible role for the wildcards, we can track a moving range of how many open brackets are currently allowed. By constantly updating the minimum and maximum possible number of open brackets as we read through the text, we can determine if a valid balance is achievable at the end.

Here's how the algorithm would work step-by-step:

  1. Imagine walking through the string from left to right while keeping track of the fewest and greatest number of open brackets you could possibly have at any moment.
  2. Whenever you see a standard opening bracket, both your minimum and maximum counts go up by one because you are guaranteed to need a closing bracket later.
  3. Whenever you see a standard closing bracket, both your minimum and maximum counts go down by one because you have successfully closed a bracket.
  4. Whenever you encounter a wildcard, treat it flexibly by letting it act as an opening bracket, a closing bracket, or nothing at all, which widens your range of possible open brackets.
  5. If your maximum count ever drops below zero, it means you have encountered too many closing brackets with nothing to match them, so the string is officially broken and you can stop.
  6. Ensure your minimum count never dips below zero, because you cannot have a negative number of open brackets in reality.
  7. Once you reach the very end of the string, check if zero is safely inside your final range of possible open brackets to confirm everything balanced out perfectly.

Code Implementation

def check_valid_string(input_string):    minimum_open_brackets = 0    maximum_open_brackets = 0    for current_character in input_string:        if current_character == '(':            minimum_open_brackets += 1            maximum_open_brackets += 1        elif current_character == ')':            minimum_open_brackets -= 1            maximum_open_brackets -= 1        else:            minimum_open_brackets -= 1            maximum_open_brackets += 1        # Too many closing brackets encountered, impossible to recover balance.        if maximum_open_brackets < 0:            return False        # Minimum cannot drop below zero since we cannot have negative open brackets.        if minimum_open_brackets < 0:            minimum_open_brackets = 0    # Ensure zero is safely inside the final range to confirm full closure.    return minimum_open_brackets == 0

Big(O) Analysis

Time Complexity
O(n) – As we walk through the string of length n from left to right, we process each character exactly once with a single pass. For each character, we perform constant-time arithmetic operations to update our minimum and maximum possible open bracket counts. The cost is entirely driven by the single pass over the n characters in the input string. This results in roughly n total operations, which simplifies to Big O of n.
Space Complexity
O(1) – The algorithm only maintains a few primitive scalar variables, specifically the minimum and maximum possible counts of open brackets, to track the state as it iterates through the text. No auxiliary data structures, lists, or recursive stack frames are created. Because this constant number of tracking variables remains unchanged regardless of the length of the input string denoted as N, the auxiliary space complexity is strictly constant.

Edge Cases

Empty string input
How to Handle:
An empty string is vacuously valid and should return true immediately.
Single character string containing only an asterisk
How to Handle:
The asterisk can act as an empty string, allowing the function to return true.
String with a single unmatched parenthesis like '(' or ')'
How to Handle:
Tracking minimum and maximum open parentheses counts ensures single unmatched characters correctly evaluate to false.
String starting with a closing parenthesis such as ')('
How to Handle:
The minimum open count must never drop below zero, immediately invalidating strings that start with a closing parenthesis.
String with unbalanced extra opening parentheses like '((*'
How to Handle:
At the end of the traversal, checking that the minimum open count reaches zero ensures no unmatched opening parentheses remain.
Extremely long strings of up to one hundred thousand characters
How to Handle:
An O(n) greedy approach using constant extra space allows the solution to scale efficiently without stack overflow issues.
Strings with heavily skewed distributions consisting entirely of asterisks
How to Handle:
Treating asterisks flexibly as empty strings allows the balance range to safely span from zero to the total asterisk count.
0/5 completed