Append-Only Editor with Undo and Redo Replay
Data Structure DesignAuto-graded · 19 test casesLast updated
Simulate a tail-only text buffer with undo and redo histories, recording only edits that change the text and clearing redo on every new edit.
Replay an Editor Session
You are given a log of commands issued to a very simple text buffer. Edits only ever happen at the end of the text. Replay the commands in order, starting from an empty buffer, and return one result per command.
Commands
commands[i] is the name of the i-th command and params[i] is the list of its arguments.
| Command | Arguments | Behavior |
|---|---|---|
insert | [text] | Append text to the end of the buffer. |
delete | [k] | Remove up to k characters from the end. If k is larger than the current length, remove everything that is there. |
undo_last | [] | Reverse the most recent recorded edit. |
redo_last | [] | Re-apply the edit most recently reversed by an undo. |
get_current_content | [] | Report the current text of the buffer. |
History rules
- Keep two histories: an undo history and a redo history.
- An
insertordeleteis recorded only if it actually changes the buffer. Inserting an empty string, deleting whenk <= 0, and deleting from an empty buffer change nothing. They are not recorded and they do not clear the redo history. - A recorded edit is pushed onto the undo history, and the redo history is emptied.
- A
deletemust remember the characters it really removed, not the requestedk. For example, deleting 100 characters from a 3-character buffer records exactly those 3 characters. undo_lasttakes the newest edit from the undo history, reverses its effect on the buffer, and moves it to the redo history. If the undo history is empty, nothing happens.redo_lasttakes the newest edit from the redo history, applies it again, and moves it back to the undo history. If the redo history is empty, nothing happens. Calling it repeatedly after the redo history runs out has no further effect.- If a command name is not one of the five above, raise
ValueError.
Output
Return a list with one entry per command, in order:
insert,delete,undo_last, andredo_lastproduceNone, whether or not they changed anything.get_current_contentproduces the current text as a string.
Constraints
len(commands) == len(params).- Every
inserthas exactly one string argument. Everydeletehas exactly one integer argument, which may be zero, negative, or far larger than the buffer length. - Undo and redo may be issued when their histories are empty.
- The total number of inserted characters fits comfortably in memory.
- Aim for work proportional to the characters actually touched by each command, not to the requested
kor to the whole history.
Examples
Example 1
Input: simulate_editor_session(['insert', 'get_current_content', 'undo_last', 'get_current_content', 'redo_last', 'get_current_content'], [['hello'], [], [], [], [], []])
Output: [None, 'hello', None, '', None, 'hello']
Example 2
Input: simulate_editor_session(['insert', 'insert', 'delete', 'get_current_content', 'undo_last', 'get_current_content', 'undo_last', 'get_current_content'], [['abcdef'], ['XYZ'], [4], [], [], [], [], []])
Output: [None, None, None, 'abcde', None, 'abcdefXYZ', None, 'abcdef']
Example 3
Input: simulate_editor_session(['delete', 'undo_last', 'redo_last', 'get_current_content', 'redo_last', 'get_current_content'], [[100], [], [], [], [], []])
Output: [None, None, None, '', None, '']
Hints
Hint 1
All changes happen at the end of the text, so the buffer behaves like a stack of characters. A Python list of characters can be extended or truncated at the tail cheaply.
Hint 2
Store each recorded edit as a pair (kind, text). For an insert the text is what was added. For a delete it is the characters that were really removed. That alone is enough to apply the edit or build its inverse.
Hint 3
Skip edits that change nothing, and clamp delete to min(max(k, 0), len(buffer)). Beware that del buf[-0:] wipes the whole list, so never run a truncation with length zero. Clear the redo history only when an edit is recorded.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Every edit touches only the end of the text, so the buffer can be a list of characters used like a stack. Appending and truncating at the tail costs time proportional to the number of characters involved, and nothing ever shifts.
Each recorded edit is stored as a small pair (kind, text):
| Record | Applying it | Its inverse |
|---|---|---|
("insert", text) | append text | remove len(text) characters from the end |
("delete", removed) | remove len(removed) characters from the end | append removed |
The pair carries all the information needed to apply the edit or to reverse it. The delete record stores the characters it actually removed, because undo needs them to restore the text.
The commands then work as follows:
- insert / delete: compute the effective change. If the buffer changes, apply it, push the record on the undo stack, and clear the redo stack. Otherwise do nothing at all, so the redo stack survives. For delete, the effective count is
min(max(k, 0), len(buf)). - undo_last: pop the undo stack, apply the inverse, and push the same record on the redo stack.
- redo_last: pop the redo stack, apply the record again, and push it back on the undo stack.
- get_current_content: join the characters into a string.
- Undo or redo with an empty stack does nothing, and an unknown command raises
ValueError.
Why it is correct
Invariant: applying the undo stack's records from bottom to top to an empty buffer gives the current buffer, and the redo stack holds undone records with the most recently undone on top.
- A recorded edit is applied and pushed, so the first half of the invariant holds. Clearing redo is needed because the undone edits no longer follow from the new current state.
- Undo removes the newest record and applies its exact inverse, so the buffer equals the result of the remaining stack. An inserted text is always the final
len(text)characters at that moment, because every later edit has already been undone. A removed text is put back verbatim. - Redo runs when the buffer is exactly in the state the record was originally applied to, so re-applying it is valid.
Skipping no-op edits matters for two reasons. Undo should never spend a step on something that changed nothing. Also, recording an empty insert would later execute del buf[-0:], and since -0 == 0 that would erase the whole buffer. Because only non-empty records are stored, every stored text has length at least 1.
Complexity
Let m be the length of an inserted text and c = min(k, n) the number of characters actually deleted from a buffer of length n.
insert: O(m)delete: O(c), independent of how largekisundo_last/redo_last: O(length of the record)get_current_content: O(n)- Space: O(n) for the buffer plus O(total characters in recorded edits) for the histories.
Storing deltas rather than full snapshots keeps each history entry proportional to the size of the edit instead of the size of the document.
Reference solution
from typing import List, Optional
def simulate_editor_session(commands: List[str], params: List[List[object]]) -> List[Optional[str]]:
buf = []
undo_stack = []
redo_stack = []
out = []
for name, args in zip(commands, params):
if name == "insert":
text = args[0]
if text:
buf.extend(text)
undo_stack.append(("insert", text))
redo_stack.clear()
out.append(None)
elif name == "delete":
k = args[0]
count = min(max(k, 0), len(buf))
if count:
removed = "".join(buf[-count:])
del buf[-count:]
undo_stack.append(("delete", removed))
redo_stack.clear()
out.append(None)
elif name == "undo_last":
if undo_stack:
kind, text = undo_stack.pop()
if kind == "insert":
del buf[-len(text):]
else:
buf.extend(text)
redo_stack.append((kind, text))
out.append(None)
elif name == "redo_last":
if redo_stack:
kind, text = redo_stack.pop()
if kind == "insert":
buf.extend(text)
else:
del buf[-len(text):]
undo_stack.append((kind, text))
out.append(None)
elif name == "get_current_content":
out.append("".join(buf))
else:
raise ValueError(f"Unknown operation: {name}")
return out