problems / 196

Bracket Expression Parser

easy parsing stack bracket-sequences 1000 ms · 256 MB

Bracket Expression Parser

You are given a string containing only bracket characters: (, ), [, ], {, and }.

Determine if the bracket expression is valid or report the position of the first error.

A valid bracket expression satisfies:

  1. Every opening bracket has a matching closing bracket of the same type.
  2. Brackets are properly nested (no crossing pairs like ([)]).
  3. There are no unmatched closing brackets.
  4. There are no unmatched opening brackets at the end.

Input

A single line containing the bracket expression. The string is non-empty and contains only characters from {, }, [, ], (, ).

Output

If the expression is valid, print valid.

Otherwise, print the 1-indexed position of the first bracket that causes an error.

An error is defined as:

  • A closing bracket with no matching opening bracket of the same type (report the position of this closing bracket).
  • A closing bracket that doesn't match the most recent unmatched opening bracket (report the position of this closing bracket).
  • An unmatched opening bracket at the end of the string (report n+1, where n is the length of the string).

Constraints

  • 1 ≤ n ≤ 10^6 (length of the bracket expression)

Example 1

Input

()[]{}

Output

valid

Example 2

Input

([)]

Output

3

Hints · reveal one at a time if you're stuck

Hint 1

Scan left to right and keep the unmatched opening brackets in order. When a closing bracket arrives, which opening bracket must it pair with?

Hint 2

There are three ways to fail: a closing bracket with nothing open, a closing bracket that does not match the most recent opener, and openers left over at the end. The first two can be detected at the moment they occur.

Hint 3

Leftover openers at the end are reported as position n+1, not as the position of any opener. Report all other errors using the 1-indexed position of the bracket.

report an issue Prefer your own editor? sooks prep 196 (CLI)
Sign in to run code

Run your code on the examples, or submit it against every test.