Skip to main content

Valid Parenthesis String

The string holds only '(', ')' and '*'. A '*' can stand for '(', ')' or nothing. Return True if some choice for every '*' makes the parentheses match up. Example: "(*))" => True, "(*)" => True, ")*(" => False

Valid Parenthesis String is a dynamic programming question: define the state cleanly and the transitions usually follow. Interviewers love it because it reveals your state-and-transition thinking and your edge-case discipline. Once you define the right state, the transitions usually write themselves.

Examples

You write

check_valid_string(s: str)

  1. Example 1

    Input
    s = "(*))"
    returns
    true
  2. Example 2

    Input
    s = "(*)"
    returns
    true

The pattern behind it

Strings

I reach for it when

  • The input is text and the answer is a count, a substring or a new string.
  • You need to compare, reverse or rebuild characters.

Say this before you type. Say which array pattern the string is hiding before you touch a character.

All 51 Strings problems

Stack

I reach for it when

  • Things must close in the reverse order they opened.
  • You need the nearest earlier or later item that is bigger or smaller.

Say this before you type. Say what each item on the stack is waiting for, and what lets you pop it.

All 17 Stack problems

Meet Coco

Coco is an AI study partner, not a person. She listens while you explain your code, asks what a line does and never hands you the fix. Sign in free to type with Coco, up to a daily limit. The editor and Run stay open without an account. Anyone can open the editor and run their code.

1Validate Stringmedium