Skip to main content
Back to problems
Leetcode
Medium
Stacks
Greedy
Dynamic Programming
Strings
Google
Meta
Valid Parenthesis String

Determine whether a parenthesis string can be made valid when * may act as (, ), or an empty string.

Acceptance 0%
Also Available On
Other platform versions and source mappings for the same problem.

Valid Parentheses String

gfg
Primary
Problem Statement

Problem

You are given a string s containing only the characters (, ) and *.

A string is valid if:

  • every opening parenthesis has a matching closing parenthesis,
  • parentheses are properly nested,
  • and the empty string is considered valid.

Each * character can be treated as:

  • (, or
  • ), or
  • an empty string.

Return true if it is possible to replace every * so that the resulting string is valid. Otherwise, return false.

Notes

  • You must consider all * characters.
  • The replacement choices may differ for each *.
  • The final string after replacements must be a well-formed parenthesis sequence.

Input Format

  • A single string s.
  • s consists only of '(', ')', and '*'.

Output Format

  • Return true if s can be transformed into a valid parenthesis string.
  • Otherwise, return false.

Constraints

  • 1 <= s.length <= 100
  • s[i] is one of '(', ')', '*'
Examples
Sample cases returned by the problem API.

Example 1

Input

s = "(*)"

Output

true

Explanation

Treat * as an empty string, giving (), which is valid.

Example 2

Input

s = "(*))"

Output

true

Explanation

Treat * as (, giving (()), which is valid.

Show 1 more example

Example 3

Input

s = "((*)"

Output

true

Explanation

Treat * as ), giving ()(), which is valid.

Premium problem context

Unlock deeper context for this problem

Premium adds guided hints, editorial links, similar variants, discussion resources, and concept maps so you can understand why a problem matters, not just solve it once.

Guided hints
Editorial and discussion links
Concept map and variants
Sign in to unlock
Track your progress
Sign in to bookmark this problem, save notes, and manage its revision plan.