Dataford
Interview QuestionsInterview GuidesExperiencesMock InterviewsPricing
Get started

Stack-Based Text Editor Undo/Redo

EasyPython00:00
Practice interviewer
In session
5 left
00:00

Your question is Stack-Based Text Editor Undo/Redo. Start with the requirements on the right.

Run and submit as often as you like. When you're ready, talk me through your approach or go straight to the code.

You need to log in / sign up to run or submit.

Problem

Implement the editing history for a simple text editor used within a Lutron Designer configuration workflow. The editor supports inserting text, deleting characters, undoing edits, and redoing previously undone edits.

Use two stacks: an undo stack and a redo stack. Every successful insert or delete saves the text state before the edit on the undo stack and clears the redo stack. An undo restores the most recent previous state and places the current state on the redo stack. A redo restores the most recently undone state and places the current state on the undo stack. If an undo or redo is requested when its stack is empty, do nothing.

Formal Specification

Implement process_editor(initial_text, operations).

  • initial_text is a string.
  • operations is a list of dictionaries.
  • An insert operation has the form {"type": "insert", "index": i, "text": s}.
  • A delete operation has the form {"type": "delete", "index": i, "count": c}.
  • History operations have the form {"type": "undo"} or {"type": "redo"}.
  • Return the final editor text as a string.
  • Indices are valid for the current text, and delete ranges are valid.

Example 1: initial_text = "Lutron", operations = [{"type":"insert","index":6,"text":" Hub"},{"type":"undo"}] returns "Lutron" because the insertion is undone.

Example 2: initial_text = "abc", operations = [{"type":"delete","index":1,"count":1},{"type":"undo"},{"type":"redo"}] returns "ac" because the deletion is undone and then reapplied.

Constraints

  • 0 <= len(initial_text) <= 10^5
  • 0 <= len(operations) <= 10^4
  • Each operation type is one of insert, delete, undo, or redo
  • Insert indices are valid for the current text
  • Delete indices and counts describe a valid range

Function Signature

def process_editor(initial_text, operations):
Your solutionPython 3
You need to log in / sign up to run or submit.
Run your code to see test output