VOOZH about

URL: https://www.geeksforgeeks.org/projects/implement-undo-and-redo-features-of-a-text-editor/

⇱ Implement Undo and Redo - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Implement Undo and Redo

Last Updated : 15 Sep, 2025

Given an array arr[], consisting of operation of the following types:

  • append('X') : Write a character X into the document.
  • undo() : Erases the last change made to the document.
  • redo(): Restores the most recent undo() operation performed on the document.
  • read() : Return the contents of the current documents.

Examples:

Input: arr[] = [append('A'), append('B'), append('C'), undo(), read(), redo(), read()]
Output: [AB, ABC]
Explanation:
Perform append('A') on the document. Therefore, the document contains only “A”.
Perform append('B') on the document. Therefore, the document contains “AB”.
Perform append('C') on the document. Therefore, the document contains “ABC”.
Perform undo() on the document. Therefore, the document contains “AB”.
Perform read() on the document. Return the contents of the document, i.e. “AB”
Perform redo() on the document. Therefore, the document contains “ABC”.
Perform read() on the document. Return the contents of the document, i.e. “ABC”

[Approach] Using Stack - O(n) Time and O(n) Space

The idea is to maintain the character whenever we perform an undo(). Remove the last character from the current string and push it onto the stack (redo). The stack stores characters in the order they were undo the last undo character is on top. When performing a redo(), pop the top character from the redo stack and append it back to the current string.

Whenever a new character is written, the redo stack is cleared because previous undo characters are no longer valid.

Note: In Java and C#, the String class is immutable, meaning once a string object is created, its value cannot be changed. To solve this, we use StringBuilder.


Output
AB ABC 
Comment