Taro Logo

Valid Parentheses

#6 Most AskedEasy
58 views
Topics:
StringsStacks

Given a string s containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.

An input string is valid if:

  1. Open brackets must be closed by the same type of brackets.
  2. Open brackets must be closed in the correct order.
  3. Every close bracket has a corresponding open bracket of the same type.

Example 1:

Input: s = "()"

Output: true

Example 2:

Input: s = "()[]{}"

Output: true

Example 3:

Input: s = "(]"

Output: false

Example 4:

Input: s = "([])"

Output: true

Example 5:

Input: s = "([)]"

Output: false

Constraints:

  • 1 <= s.length <= 104
  • s consists of parentheses only '()[]{}'.

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. Can the input string be empty, and if so, should it be considered valid?
  2. Are we guaranteed that the input string will only ever contain the six specified bracket characters, or could there be whitespace or invalid characters?
  3. What is the maximum expected length of the input string, and are there strict memory constraints we need to keep in mind?
  4. Should we handle unbalanced closing brackets appearing at the very beginning of the string, such as ")()", and ensure it returns false immediately?
  5. Is the input guaranteed to be encoded in standard ASCII/UTF-8, or could there be multi-byte characters?

Brute Force Solution

Approach

Imagine you have a mixed-up string of opening and closing brackets and you need to figure out if every opening bracket is properly closed and matched in the right order. The brute force approach involves trying every possible way to pair up and cancel out matching brackets until nothing is left or you run out of options.

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

  1. Start by looking at the entire sequence of brackets from beginning to end.
  2. Repeatedly search through the entire sequence to find any pair of matching opening and closing brackets that are right next to each other.
  3. Whenever you find a side-by-side matching pair, pretend to erase them both from the sequence.
  4. Take the remaining pieces and push them back together to form a new, shorter sequence.
  5. Repeat this entire erasure process from the very beginning on the new shorter sequence.
  6. Keep doing this until you can no longer find any side-by-side matching pairs.
  7. Finally, look at what is left over and decide that the brackets were valid only if every single one of them was successfully erased.

Code Implementation

def is_valid(bracket_string):
    # We repeatedly mutate the string because valid pairs must be adjacent to collapse first
    current_sequence = bracket_string
    
    while True:
        previous_length = len(current_sequence)
        
        current_sequence = current_sequence.replace("()", "")
        current_sequence = current_sequence.replace("[]", "")
        current_sequence = current_sequence.replace("{}", "")
        
        # Stopping early prevents infinite loops when no more adjacent pairs can be erased
        if len(current_sequence) == previous_length:
            break
            
    # Only a completely empty string proves every opening bracket found its correct match
    return len(current_sequence) == 0

Big(O) Analysis

Time Complexity
O(n²) – In the worst-case scenario, we must repeatedly scan through the entire shrinking string of length n to find and remove a single adjacent matching pair of brackets. Because each successful removal shortens the string by two characters, we might need to perform up to n/2 passes over the sequence. Each pass requires scanning up to n characters to locate the adjacent pairs. This yields roughly n multiplied by n/2 operations in total, which simplifies to a quadratic time complexity of O(n²).
Space Complexity
O(n) – The brute force process repeatedly stores intermediate sequences and shortened strings as matching pairs are erased. In the worst case where the string contains only opening brackets of length N, the temporary strings and shrinking sequences held in memory grow proportionally with the input size. Therefore, the extra memory required scales linearly relative to the input length N, leading to an auxiliary space complexity of O(n).

Optimal Solution

Approach

The optimal strategy for checking valid parentheses mimics how a human would check a nested structure by keeping track of opening symbols as they appear. As closing symbols show up, they must match the most recently seen opening symbol, ensuring everything is properly nested and closed in the correct order.

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

  1. Imagine you are holding a mental tray or stacking plates as you read through the string from left to right.
  2. Whenever you encounter an opening symbol, place it onto your mental stack because it will need to be closed later.
  3. Whenever you encounter a closing symbol, look at the most recent opening symbol you placed on your stack.
  4. Check if the closing symbol matches the type of that most recent opening symbol. If they do not match, or if your stack is empty because there was no opening symbol waiting, you immediately know the sequence is invalid.
  5. If they do match, remove that opening symbol from your stack and continue reading the rest of the string.
  6. Once you reach the very end of the string, check your stack one last time to make sure no opening symbols were left behind.
  7. If the stack is completely empty, every opening symbol successfully found its matching closing symbol in the correct order, meaning the string is valid.

Code Implementation

def is_valid_parentheses(input_string):
    opening_to_closing_map = {')': '(', '}': '{', ']': '['}
    opening_symbol_stack = []

    # We record opening symbols so we can match them against future closing symbols.
    for current_character in input_string:
        if current_character in opening_to_closing_map.values():
            opening_symbol_stack.append(current_character)
        elif current_character in opening_to_closing_map.keys():
            # A closing symbol requires an immediate matching opening symbol to be valid.
            if not opening_symbol_stack or opening_symbol_stack[-1] != opening_to_closing_map[current_character]:
                return False
            
            opening_symbol_stack.pop()

    # Unmatched opening symbols mean the structure was never properly closed.
    return len(opening_symbol_stack) == 0

Big(O) Analysis

Time Complexity
O(n) – As we iterate through the input string of size n from left to right, we perform a constant time push or pop operation on our stack for each character. Each of the n characters is processed at most once, driving the linear cost of the algorithm. Summing these constant time operations across all n elements yields approximately 1 * n operations, which simplifies to Big O of n.
Space Complexity
O(N) – The auxiliary space is driven by the stack data structure used to keep track of opening symbols as we iterate through the string. In the worst-case scenario where the string contains entirely opening symbols like (((((, every character is pushed onto the stack, resulting in an auxiliary stack of size N, where N is the length of the string. Therefore, the memory required scales linearly with the input size N, simplifying to Big O of N notation.

Edge Cases

Empty string input
How to Handle:
Return true immediately since an empty string has no unmatched brackets.
String with a single character
How to Handle:
Return false because a single bracket can never be closed.
String starting with a closing bracket
How to Handle:
The stack will be empty when attempting to pop, signaling an immediate invalid state and returning false.
String with only opening brackets
How to Handle:
The loop finishes with elements remaining in the stack, which is caught at the end by checking if the stack is empty.
Mismatched closing and opening bracket types
How to Handle:
The popped element from the stack will not match the current closing bracket, resulting in an immediate false return.
Maximum-sized inputs with deep nesting
How to Handle:
The stack grows proportionally to the input size, operating in O(N) time and space complexity without stack overflow risks.
Interleaved or overlapping bracket types
How to Handle:
The LIFO nature of the stack naturally enforces correct nesting order by ensuring the most recent open bracket is closed first.
Strings with odd lengths
How to Handle:
An odd-length string can never have all brackets properly closed, so returning false early or relying on the final stack check handles this efficiently.
0/6 completed