Back to Practice Dashboard
Top 150 InterviewEasy

Valid Parenthesis String

Learn how to solve the 'Valid Parenthesis String' problem. This detailed resource details brute force and optimized approaches.

Problem Statement

Easy

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.

Write a function checkValidString(s: str) -> bool.

Constraints
  • 1 <= len(s) <= 100
  • s contains only '(', ')' and '*'

Examples

Example 1
Input
s = "()"
Output
True
Explanation

Matches perfectly.

Example 2
Input
s = "(*)"
Output
True
Explanation

Treat '*' as empty string.

Example 3
Input
s = "(*))"
Output
True
Explanation

Treat '*' as '('.

Need a Hint?
Analyze the input constraints. Try sorting first (O(n log n)) or using a hash map/set to track seen elements in O(n) time.
Edge Cases to Watch
  • Empty list or null input variables
  • Single item lists/arrays
  • Extremely large input bounds causing integer or stack overflow

Ready to Solve?

Open the problem in PyRun's browser-based Python editor. Your code runs fully offline — no server required.

Open in Editor