SDE Path

Text Editor with Undo/Redo

Medium

Text Editor with Undo/Redo

Implement append/delete editing with full undo and redo — the Command pattern's home turf.

Requirements

  • append and delete are edits; undo/redo navigate edit history; read inspects.
  • A new edit clears the redo stack — after undoing twice and typing something new, the two undone edits are unreachable (exactly how every real editor behaves).
  • undo/redo beyond the ends of history are silent no-ops.
  • delete k with k larger than the document deletes everything (and is still one undoable edit).

API to implement

Implement the class TextEditor. The I/O driver is already written in the starter code — it parses the command script below and calls your methods. You only implement the class.

| Command | Returns | Behavior | |---|---|---| | append <text> | — | Append text (no spaces) to the document. Clears the redo history. | | delete <k> | — | Delete the last k characters (all of them if fewer exist). Implemented as the method remove (delete is a keyword in C++). Clears the redo history. | | undo | — | Revert the most recent un-undone edit. No-op if there is nothing to undo. Undone edits become redoable. | | redo | — | Re-apply the most recently undone edit. No-op if there is nothing to redo. | | read | string | Return the current document, or - if it is empty. |

Input format

The first line contains Q, the number of operations. Each of the next Q lines is one command as listed above. String arguments contain no spaces.

Output format

For each command with a non-void return, print its result on its own line, in order. The driver does this for you — your methods just return values.

This is a design problem: the hidden tests exercise edge cases and interaction sequences, not performance tricks. Model the state cleanly and the tests will pass.

Sample cases

Example 1
Input
11
append hello
append world
read
undo
read
redo
read
undo
undo
undo
read
Expected output
helloworld
hello
helloworld
-
Example 2
Input
8
append abc
delete 2
read
undo
read
append z
redo
read
Expected output
a
abc
abcz