Netflix questions

Text Editor

NetflixOnsiteMedium

You design a text editor that keeps its document as a single string. The document starts empty, and every edit happens at the end of the text: append adds characters there and delete removes characters from there. Each test creates one Editor instance and runs a sequence of method calls, recording every call's return value (None for methods that return nothing).

Part 1: Append, delete and undo

Implement a class Editor with these methods:

  • append(s) adds the string s to the end of the text. Returns None.
  • delete(k) removes the last k characters, or the whole text when it has fewer than k characters. Returns the number of characters actually removed.
  • undo() reverts the most recent edit that has not been undone yet and returns True, or returns False when there is no such edit. Repeated undo() calls walk back through the history one edit at a time.
  • text() returns the current text.

An edit is an append, or a delete that removed at least one character. A delete that removes nothing is not an edit: it is not recorded, so undo() never reverts it.

  1. Example 1
    init
    []
    operations
    [["append",["hello"]],["append",[" world"]],["text",[]],["delete",[3]],["text",[]],["undo",[]],["text",[]],["undo",[]],["text",[]],["undo",[]],["text",[]],["undo",[]],["undo",[]]]
    Output
    [null,null,"hello world",3,"hello wo",true,"hello world",true,"hello",true,"",false,false]

    Why: delete(3) trims the text to hello wo. Each undo() reverts one edit in reverse order: the delete, then the append of world, then the append of hello. The last two undo() calls find no un-reverted edit and return False.

Constraints

  • 1 <= len(operations) <= 10^4
  • 1 <= len(s) <= 100
  • 1 <= k <= 10^4
  • each character of s satisfies 'a' <= s[i] <= 'z'
Import your own questions
Paste a question you were asked and get a full problem: statement, tests and a checked solution.
Import a question