Valid Parenthesis String

Valid Parenthesis String Problem

You are given a string s consisting of only three types of characters: ‘(‘‘)’, and ‘*’. Return true if the string is valid; otherwise, return false.

A string is considered valid if it satisfies all the following conditions:

  • Each ‘(‘ must have a matching ‘)’ and each ‘)’ must have a matching ‘(‘.
  • ‘(‘ must always appear before its matching ‘)’.
  • ‘*’ character can be treated as ‘(‘, ‘)’, or an empty string (” “).
Valid Parenthesis String Problem

Examples related Valid Parenthesis String

Example 1:

Example 2:

Constraints:

       1 <= s.length <= 100

Methods to Solve Valid Parenthesis String

There are mainly 6 approach to solve Reverse Nodes In K Group problem:

  1. Recursion Method
  2. Dynamic Programming Top Down
  3. Dynamic Programming Bottom Up
  4. Dynamic Programming Spaced Optimized
  5. Stack
  6. Greedy

1. Recursion Method

  • This approach explores all possible interpretations of the * character (as (, ), or empty) by recursively validating each case. It is straightforward but can be slow due to redundant computations.
  • Time complexity: O(3^n)
  • Space complexity: O(n)

Code:

2. Dynamic Programming Top Down Method

  • Use memorization to optimize recursion by storing already-computed results for specific states, avoiding repeated calculations.
  • This reduces redundant work and speeds up the solution.
  • Time complexity: O(n^2)
  • Space complexity: O(n^2)

Code:

3. Dynamic Programming Bottom Up Method

  • Build a table to solve the problem iteratively, starting from smaller subproblems and combining results. It systematically tracks valid states for substrings, ensuring efficient validation.
  • Time complexity: O(n^2)
  • Space complexity: O(n^2)

Code:

4. Dynamic Programming Space Optimized
Method

  • This approach improves the Bottom-Up method by reducing the memory usage to a single dimension, keeping track of only necessary information for validating the string.

  • Time complexity: O(n^2)
  • Space complexity: O(n)

Code:

5. Stack Method

  • Iteration method involves reversing k nodes in a group iteratively.

    Use a stack to track unmatched parentheses, and when encountering *, decide dynamically whether to treat it as ( or ) while maintaining balance.

  • Time complexity: O(n)
  • Space complexity: O(n)

Code:

6. Greedy Method

  • This approach keeps track of the possible range of open parentheses using counters and adjusts them as the string is processed. It’s efficient and works without extra space.

  • Time complexity: O(n)
  • Space complexity: O(1)

Code:

More Articles