Text Editor with Snapshots Medium · Topics · Company Tags · Hints
Design a text editor that maintains a sequence of characters and supports a set of five operations. Your implementation should handle up to 1000 total operations efficiently, with each text addition not exceeding 1000 characters in length.
Operations:
add_text(text) — Appends the string text to the current content of the editor.delete_text(count) — Removes the last count characters from the current content. If count exceeds the current length, delete all characters.undo_delete() — Restores the characters that were removed by the most recent delete_text operation. If there is no previous delete to undo, the editor content remains unchanged. This operation does not stack — only the immediately preceding delete can be undone, and calling it again without an intervening delete has no effect.take_snapshot() — Captures the current editor content and assigns it a unique snapshot ID. The first snapshot taken receives ID 0, the next receives ID 1, and so on.restore_snapshot(snapshot_id) — Replaces the current editor content with the content stored in the snapshot identified by snapshot_id. If the provided ID does not correspond to any existing snapshot, the editor content remains unchanged.Assume all input text strings consist of printable characters. You may choose any underlying data structure that supports these actions efficiently.
Example 1:
Input:
editor = TextEditor()
editor.add_text("hello")
editor.take_snapshot()
editor.add_text(" world")
editor.delete_text(6)
editor.undo_delete()
editor.take_snapshot()
print(editor.content)
editor.restore_snapshot(0)
print(editor.content)
Output:
hello world
hello
Explanation: After adding "hello", a snapshot is taken (ID 0). Appending " world" yields "hello world". Deleting 6 characters removes " world", leaving "hello". Undoing the delete restores the full string. A new snapshot (ID 1) captures "hello world". Restoring snapshot 0 reverts the content back to "hello".
Example 2:
Input:
editor = TextEditor()
editor.add_text("abc")
editor.take_snapshot()
editor.add_text("def")
editor.delete_text(3)
editor.undo_delete()
editor.take_snapshot()
editor.restore_snapshot(1)
print(editor.content)
Output:
abcdef
Explanation: Start with "abc". Snapshot 0 captures it. Append "def" to get "abcdef". Delete 3 characters, removing "def" and leaving "abc". Undo the delete to bring back "abcdef". Take snapshot 1. Restore snapshot 1, which holds "abcdef", so the content stays the same.
Example 3:
Input:
editor = TextEditor()
editor.add_text("x")
editor.delete_text(5)
editor.undo_delete()
print(editor.content)
editor.delete_text(0)
print(editor.content)
Output:
x
x
Explanation: After adding "x", deleting 5 characters leaves an empty editor. Undoing the delete restores "x". A subsequent delete of 0 characters does nothing, and since there is no valid delete to undo, another undo_delete call has no effect.
Constraints:
text in any add_text call ≤ 1000 characters.