CodeArchon

mediumGreedyFacebookMicrosoft

Bracket Elasticity Check

A parser verifies that a mix of '(' , ')' and wildcard '*' (which can be '(' , ')' or empty) is a valid bracket string.

Given a string of '(', ')', '*', return true iff some choice for each '*' makes the brackets balanced.

Choose approach

(
0
i
*
1
)
2
)
3
Maprange
lo→1
hi→1
1/5
Narrationstep 1 of 5

i=0 ('('): lo=1, hi=1.

1def checkValidString(s):
2 lo = hi = 0
3 for c in s:
4 if c == '(': lo += 1; hi += 1
5 elif c == ')': lo -= 1; hi -= 1
6 else: lo -= 1; hi += 1
7 if hi < 0: return False
8 lo = max(lo, 0)
9 return lo == 0
Variables
i=0
lo=1
hi=1

How to think about it

  1. Clip lo at 0 (never negative).
  2. hi<0 means ')' exceeded any possibility.

Edge cases to catch in interview

  • Empty string -> true.
  • All stars -> true.

Examples

Example 1true
{"s":"(*)","values":["(","*",")"]}

Try your own input

SpacePlay / pause
← / →Previous / next step
RReset to start
. or >Cycle speed