A drawing app keeps undo history, but long sessions would use too much memory, so it only keeps the limit most recent earlier states.
Implement BoundedHistory: new BoundedHistory(initial, limit) starts at state initial. commit(state) saves the current state for undo, moves to state, and clears redo; if more than limit states are now saved for undo, the oldest is dropped. undo() and redo() move one step and return the current state (unchanged if there's nothing to do). canUndo() returns whether undo would change anything.
States are strings.
Each example lists the calls in order, then each call's arguments. The first call creates the object with new BoundedHistory(…); the output lists what each call returns (null for the constructor and for methods that return nothing).
Input: ["BoundedHistory","commit","commit","commit","undo","undo","undo","canUndo"] [["s0",2],["s1"],["s2"],["s3"],[],[],[],[]] Output: [null,null,null,null,"s2","s1","s1",false]
Only two earlier states fit, so s0 was dropped when s3 was committed. Undo stops at s1.
Input: ["BoundedHistory","canUndo","commit","canUndo","undo","redo"] [["a",5],[],["b"],[],[],[]] Output: [null,false,null,true,"a","b"]
One commit makes undo possible; undo and redo move between a and b.
1 <= limit <= 1000; up to 10^4 method calls.Run tries your code on the examples. Submit runs every test, including hidden edge cases, and solves the problem when they all pass.
Ctrl + Enter runs, Ctrl + Shift + Enter submits (⌘ on a Mac).
I'm here to help with #734 History with a Size Limit. I give hints, never the solution, so you get to solve it yourself. Ask for a hint, select code to ask about it, or press Ask Tuto why on a failing test.
Your first 3 answers need no account. for free to keep asking.