Figma questions

Text Editor with Undo

FigmaPhone screenMedium

You will build a class TextEditor that holds a piece of text, initially empty. Positions are zero-based indexes into the text.

An edit op is a list of one of these forms:

  • ["insert", index, text] inserts text at index
  • ["delete", start, end] removes the characters from start up to but not including end
  • ["replace", start, end, text] replaces that range with text

Each test drives one TextEditor instance through a sequence of calls.

Part 1: Apply and undo

Implement apply(op), get_text() and undo().

apply applies one edit to the text. get_text returns the current text. undo reverts the most recent applied edit that has not been undone, restoring the text exactly as it was before that edit; if there is nothing to revert, it does nothing.

Each call to apply is one undoable step. apply and undo return None.

  1. Example 1
    init
    []
    operations
    [["apply",[["insert",0,"hello"]]],["get_text",[]],["apply",[["insert",5," world"]]],["get_text",[]],["undo",[]],["get_text",[]],["apply",[["replace",0,5,"bye"]]],["get_text",[]],["undo",[]],["get_text",[]],["undo",[]],["get_text",[]],["undo",[]],["get_text",[]]]
    Output
    [null,"hello",null,"hello world",null,"hello",null,"bye",null,"hello",null,"",null,""]

    Why: The first undo removes world. Undoing the replace restores all five letters of hello; the next undo removes it, and the last undo has nothing left to revert, so the text stays empty.

Constraints

  • 0 <= len(operations) <= 10^4
  • 0 <= index <= len(text) at the time of each insert
  • 0 <= start <= end <= len(text) at the time of each delete or replace
  • The text never exceeds 10^5 characters
Import your own questions
Paste a question you were asked and get a full problem: statement, tests and a checked solution.
Import a question
Text Editor with Undo: Figma interview question | LoopCoach