Undo Text Editor - Problem

Design and implement a simple text editor that supports the following operations:

  • Type: Add a character to the end of the current text
  • Delete: Remove the last character from the current text
  • Undo: Revert the text to its state before the last operation

Implement the TextEditor class with the following methods:

  • type(char) - adds the character to the end of the text
  • delete() - removes the last character from the text
  • undo() - undoes the last operation (type or delete)
  • getText() - returns the current text as a string

Your implementation should efficiently handle multiple undo operations and maintain the history of text states.

Input & Output

Example 1 — Basic Operations
$ Input: operations = [["type","h"],["type","e"],["delete"],["undo"]]
Output: ["h","he","h","he"]
💡 Note: Type 'h' → "h", type 'e' → "he", delete last char → "h", undo delete → "he"
Example 2 — Multiple Undos
$ Input: operations = [["type","a"],["type","b"],["undo"],["undo"]]
Output: ["a","ab","a",""]
💡 Note: Type 'a' → "a", type 'b' → "ab", undo → "a", undo again → ""
Example 3 — Delete and Undo
$ Input: operations = [["type","x"],["delete"],["undo"],["delete"]]
Output: ["x","","x",""]
💡 Note: Type 'x' → "x", delete → "", undo delete → "x", delete again → ""

Constraints

  • 1 ≤ operations.length ≤ 100
  • Each operation is one of: ["type", char], ["delete"], or ["undo"]
  • char is a lowercase English letter

Visualization

Tap to expand
Undo Text Editor Problem OverviewINPUT OPERATIONSSTACK ALGORITHMFINAL RESULTStype('h')type('e')delete()undo()Operations modifytext editor state1Push state to stack2Execute operation3Update current text4Pop for undo: O(1)STACK"he" (top)"h""" (bottom)"h""he""h""he"After type('h')After type('e')After delete()After undo() ✓Key Insight:Stack stores complete text snapshots for instant O(1) undo operationsTutorialsPoint - Undo Text Editor | Stack-Based Solution
Asked in
Google 25 Microsoft 18 Amazon 15 Apple 12
23.5K Views
Medium Frequency
~15 min Avg. Time
890 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen