Design a Text Editor

HardDesigndesign

Solve this the way you would in the interview: out loud, on a timer, with an AI interviewer asking follow-ups while you code. You get a scored report at the end.

Practice this as a mock interviewFree to start, no account needed

Problem

Simulate a text editor with a single cursor. The cursor always sits between two characters (or at either end of the text) and can never move outside the text. Implement TextEditor: - TextEditor() starts with empty text and the cursor at position 0. - addText(text) inserts text at the cursor; the cursor ends up just after the inserted text. - deleteText(k) deletes up to k characters immediately to the **left** of the cursor and returns how many were actually deleted. - cursorLeft(k) moves the cursor left by up to k positions (stopping at the start), then returns the last min(10, len) characters to the left of the cursor, where len is the number of characters to its left. - cursorRight(k) moves the cursor right by up to k positions (stopping at the end), then returns the same kind of string as cursorLeft. Aim for each call to run in O(k) time (plus the length of text for addText), independent of the total text length.

Examples

Input: ["TextEditor","addText","cursorLeft","addText","deleteText","cursorRight","deleteText","cursorLeft"] [[],["hello"],[2],["XY"],[3],[10],[10],[1]]
Output: [null,null,"hel",null,3,"helo",4,""]
After typing, the text is "hello|". Moving left 2 gives "hel|lo". Typing gives "helXY|lo"; deleting 3 removes "lXY" to leave "he|lo". Moving right stops at the end ("helo|"), deleting 10 only removes 4 characters, and moving left in empty text returns "".
Input: ["TextEditor","addText","cursorLeft","cursorRight","deleteText","cursorRight"] [[],["abcdefghijklmn"],[3],[1],[20],[5]]
Output: [null,null,"bcdefghijk","cdefghijkl",12,"mn"]
Only the last 10 characters left of the cursor are returned. Deleting 20 removes all 12 characters before the cursor, leaving "|mn"; moving right 5 stops after "mn".

Constraints

  • 1 <= text.length, k <= 40
  • `text` consists of lowercase English letters.
  • At most 2 * 10^4 calls are made in total.

What the interviewer grades

A correct solution is one of five scores. The report also grades problem understanding (did you clarify inputs and edge cases before coding), problem solving, communication while you work, code quality, and testing. See a sample report, or read up on the pattern in the lessons.

More design problems