PPractick

DSA interview question

Valid Parenthesis String (with Wildcards)

Hard · Data structures · Topics: greedy, string, stack

The problem

A template engine lets authors write * as a wildcard that can stand for (, ) or nothing at all. Before rendering, it must check whether the string can be read as balanced parentheses under some choice for each *. Trying all 3^k choices is exponential. Instead, track the range of possible open-bracket counts after each character: lo if every wildcard is used as ) when possible, and hi if every wildcard is used as (. If hi ever drops below 0, too many ) appeared. At the end, the string is valid if 0 is still reachable.

Example: "(*))" → true (the * becomes ().

Function signature

bool checkValidString(const string& s);  // characters '(', ')', '*'

Test cases

InputOutputExplanation
"()"true
"(*)"true* is empty
"(*))"true* is (
")("falseCloses before anything opens
"(((**"falseTwo wildcards can close only two of three
"**(("falseTrailing opens can't be closed

(Confirm: each * may independently be '(', ')' or empty; the empty string is valid.)

How interviewers phrase it

Clarifying questions to ask

  1. Can * be empty? (Yes.)
  2. Is the empty string valid? (Yes.)
  3. How long can s be? (Up to 100, but aim for O(n).)

Follow-ups to expect

  1. "What do lo and hi mean?"
  2. "Why clamp lo at 0?"
  3. "Why fail when hi < 0?"
  4. "Alternative approaches?"
  5. "Complexity?"

Practise questions like this with a real engineer

On Practick another engineer interviews you live for 60 minutes on a question from this bank. They have the full interviewer guide beside the call: the expected answer to every follow-up, hints to give if you stall, and a scoring rubric. You get the model solution once the session settles. It is free: interview someone for an hour and you have earned your own.

Book a free mock interview

Related questions

All 474 dsa interview questions

DSA mock interviews · System design interview questions · Free mock interview practice · Browse interviewers · Sign in