Skip to the code
+25 XP

#733 Group Keystrokes for Undo

medium

Editors don't undo one letter at a time: keystrokes typed in quick succession form one undo step. Replay a list of editor events and return the final text.

Each event is [time, "type", text], [time, "undo"], or [time, "redo"], sorted by time. The text starts empty.

  • A type event joins the current undo step if the event right before it was also a type and less than gap ms earlier. Otherwise it starts a new undo step (which, like any new change, makes undone steps impossible to redo).
  • undo restores the text from before the most recent step, if any. redo re-applies the most recently undone step, if any. After an undo or redo, the next type always starts a new step.

Write replayEditor(events, gap) that returns the final text.

Example 1

Input: events = [[0,"type","Hel"],[100,"type","lo"],[2000,"type"," world"],[2100,"undo"]], gap = 1000
Output: "Hello"

Hel and lo are 100 ms apart, so they form one step; world comes 1900 ms later and is its own step, which undo removes.

Example 2

Input: events = [[0,"type","a"],[10,"type","b"],[20,"undo"],[30,"redo"]], gap = 50
Output: "ab"

a and b are one step; undo removes both and redo brings both back.

Constraints

  • 0 <= events.length <= 10^5
  • 1 <= gap <= 10^4; typed text is 1 to 10 characters.
Saved in this browser

Run tries your code on the examples. Submit runs every test, including hidden edge cases and big inputs that check your code is fast enough, and solves the problem when they all pass.

Ctrl + Enter runs, Ctrl + Shift + Enter submits (⌘ on a Mac).