problems / 212

Text Editor Undo/Redo System

easy design simulation stack 1000 ms · 256 MB

Text Editor Undo/Redo System

You are implementing a simple text editor that supports basic operations and undo/redo functionality. The editor maintains a document (initially empty) and must support the following operations:

  • INSERT pos char: Insert character char at position pos (0-indexed). Characters to the right shift one position. If pos is out of bounds, do nothing.
  • DELETE pos: Delete the character at position pos (0-indexed). Characters to the right shift one position left. If pos is out of bounds or the document is empty, do nothing.
  • UNDO: Undo the most recent operation that modified the document (INSERT or DELETE). If there is nothing to undo, do nothing.
  • REDO: Redo the most recently undone operation. If there is nothing to redo, do nothing.
  • QUERY: Output the current state of the document.

The key constraint: when you perform any INSERT or DELETE, the redo history is cleared (as in real text editors).

Input

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

Each of the next n lines contains one operation:

  • INSERT pos char where 0 ≤ pos ≤ length and char is a lowercase letter
  • DELETE pos where pos ≥ 0
  • UNDO
  • REDO
  • QUERY

Output

For each QUERY operation, print the current document on a single line. If the document is empty, print an empty line.

Notes

  • The document starts empty.
  • When you INSERT or DELETE, the redo stack is cleared because the history branches.
  • Undo/redo are a no-op if there is nothing to undo/redo.

Example 1

Input

10
INSERT 0 a
QUERY
INSERT 1 b
QUERY
DELETE 0
QUERY
UNDO
QUERY
REDO
QUERY

Output

a
ab
b
ab
b

Example 2

Input

12
INSERT 0 h
INSERT 1 i
QUERY
UNDO
QUERY
UNDO
QUERY
INSERT 0 x
QUERY
REDO
QUERY
QUERY

Output

hi
h

x
x
x

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

Hint 1

UNDO has to reverse exactly one earlier change. For each change, what must you record at the moment you make it so that it can be reversed later?

Hint 2

Keep two stacks of past edits, one for undo and one for redo. A real change clears the redo stack, and an out-of-range command changes nothing, so it must not be recorded.

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

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