Skip to main content

Valid Parenthesis String

LeetCode 678 | Difficulty: Medium​

Medium

Problem Description​

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 `'*'`.

Topics: String, Dynamic Programming, Stack, Greedy


Approach​

Dynamic Programming​

Break the problem into overlapping subproblems. Define a state (what information do you need?), a recurrence (how does state[i] depend on smaller states?), and a base case. Consider both top-down (memoization) and bottom-up (tabulation) approaches.

When to use

Optimal substructure + overlapping subproblems (counting ways, min/max cost, feasibility).

Stack​

Use a stack (LIFO) to track elements that need future processing. Process elements when a "trigger" condition is met (e.g., finding a smaller/larger element). Monotonic stack maintains elements in sorted order for next greater/smaller element problems.

When to use

Matching brackets, next greater element, evaluating expressions, backtracking history.

Greedy​

At each step, make the locally optimal choice. The challenge is proving the greedy choice leads to a global optimum. Look for: can I sort by some criterion? Does choosing the best option now ever hurt future choices?

When to use

Interval scheduling, activity selection, minimum coins (certain denominations), Huffman coding.

String Processing​

Consider character frequency counts, two-pointer approaches, or building strings efficiently. For pattern matching, think about KMP or rolling hash. For palindromes, expand from center or use DP.

When to use

Anagram detection, palindrome checking, string transformation, pattern matching.


Solutions​

Solution 1: C# (Best: 144 ms)​

MetricValue
Runtime144 ms
Memory35.8 MB
Date2022-01-12
Solution
public class Solution {
public bool CheckValidString(string s) {
int cmin=0, cmax = 0;
for (int i = 0; i < s.Length; i++)
{
char c = s[i];
if(c == '(')
{
cmax++;
cmin++;
}
else if(c == ')')
{
cmax--;
cmin = Math.Max(0, cmin-1);
}
else
{
cmax++;
cmin = Math.Max(0, cmin-1);
}

if(cmax <0) return false;
}

return cmin == 0;
}
}

Complexity Analysis​

ApproachTimeSpace
Dynamic Programming$O(n)$$O(n)$
Stack$O(n)$$O(n)$

Interview Tips​

Key Points
  • Discuss the brute force approach first, then optimize. Explain your thought process.
  • Define the DP state clearly. Ask: "What is the minimum information I need to make a decision at each step?"
  • Consider if you can reduce space by only keeping the last row/few values.
  • Think about what triggers a pop: is it finding a match, or finding a smaller/larger element?
  • LeetCode provides 4 hint(s) for this problem β€” try solving without them first.
πŸ’‘ Hints

Hint 1: Use backtracking to explore all possible combinations of treating '*' as either '(', ')', or an empty string. If any combination leads to a valid string, return true.

Hint 2: DP[i][j] represents whether the substring s[i:j] is valid.

Hint 3: Keep track of the count of open parentheses encountered so far. If you encounter a close parenthesis, it should balance with an open parenthesis. Utilize a stack to handle this effectively.

Hint 4: How about using 2 stacks instead of 1? Think about it.