Build the text buffer behind a small code editor. It holds text and a cursor that sits between two characters (or at either end). Write a class TextBuffer:
new TextBuffer() starts with empty text and the cursor at position 0.type(text) inserts text at the cursor; the cursor ends up just after the inserted text.erase(k) deletes up to k characters to the left of the cursor and returns how many were actually deleted.moveLeft(k) moves the cursor left up to k times and returns the last min(10, n) characters to the left of the cursor, where n is how many characters are to its left.moveRight(k) moves the cursor right up to k times and returns the same kind of preview.Every call must be fast even when the text is long: its cost should depend on k or on the typed text, not on the length of the whole buffer.
Each example lists the calls in order, then each call's arguments. The first call creates the object with new TextBuffer(…); the output lists what each call returns (null for the constructor and for methods that return nothing).
Input: ["TextBuffer","type","erase","type","moveLeft","type","moveRight","moveLeft"] [[],["framework"],[4],["practice"],[8],["x"],[3],[100]] Output: [null,null,4,null,"frame",null,"framexpra",""]
After erase(4) the text is frame. Typing gives framepractice; moving left 8 puts the cursor after frame, where x is typed.
Input: ["TextBuffer","moveLeft","moveRight","erase"] [[],[3],[3],[3]] Output: [null,"","",0]
The buffer is empty, so nothing moves and nothing is deleted.
1 <= text.length, k <= 40text has lowercase letters and spaces.2 * 10^4 calls in total.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 #247 Cursor-Aware Text Buffer. 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.