problems / 215

Bracket Validation Pipeline

easy bracket-sequences stack strings simulation 1000 ms · 256 MB

Bracket Validation Pipeline

A configuration processor maintains a dynamic string of brackets and applies a stream of operations to it. After each operation, you must validate whether the bracket sequence is currently balanced.

A bracket sequence is balanced if:

  1. It contains an equal number of opening and closing brackets.
  2. At no point while reading left to right does the count of closing brackets exceed the count of opening brackets.
  3. Brackets are properly matched: ( matches with ), [ matches with ], { matches with }.

The processor supports three operations on the bracket string:

  • INSERT pos bracket: Insert the given bracket at position pos (0-indexed). Existing characters from position pos onward shift right.
  • DELETE pos: Remove the character at position pos.
  • VALIDATE: Check if the current bracket sequence is balanced. Output YES or NO.

Input

The first line contains n (1 ≤ n ≤ 1000), the number of operations.

Each of the next n lines describes an operation:

  • INSERT pos bracket: Insert a bracket (one of (, ), [, ], {, }) at position pos (0 ≤ pos ≤ current length).
  • DELETE pos: Delete the bracket at position pos (0 ≤ pos < current length).
  • VALIDATE: Validate the current sequence.

Output

For each VALIDATE operation, print YES if the sequence is balanced, NO otherwise.

Constraints

  • 1 ≤ n ≤ 1000
  • After all operations, the string length is at most 10000
  • Position indices are valid (0 ≤ pos ≤ string length for INSERT, 0 ≤ pos < string length for DELETE)

Example 1

Input

8
INSERT 0 (
VALIDATE
INSERT 1 )
VALIDATE
DELETE 0
VALIDATE
INSERT 0 (
VALIDATE

Output

NO
YES
NO
YES

Example 2

Input

9
INSERT 0 (
INSERT 1 [
INSERT 2 ]
VALIDATE
INSERT 3 )
VALIDATE
DELETE 1
DELETE 1
VALIDATE

Output

NO
YES
YES

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

Hint 1

Each VALIDATE only looks at the current string. Which bracket property can be checked by reading left to right and remembering only what is still open?

Hint 2

Use a stack: push each opening bracket, and let each closing bracket match the top of the stack and pop it, or fail if it doesn't match. The sequence is balanced only if the stack is empty at the end. Rebuilding the stack for each VALIDATE is fast enough at these limits.

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

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