HardNo. 2296
Design a Text Editor — LeetCode 2296 Python Solution
- Pattern
- Linked List
- Topics
- Stack, Design, Linked List, String, Doubly-Linked List, Simulation
- Reading time
- 7 min
- Source
- leetcode.com
The problem
Design a text editor with a cursor that can do the following: Add text to where the cursor is. Delete text from where the cursor is (simulating the backspace key).
Example
- Input
- ["TextEditor", "addText", "deleteText", "addText", "cursorRight", "cursorLeft", "deleteText", "cursorLeft", "cursorRight"]
- Output
- [null, null, 4, null, "etpractice", "leet", 4, "", "practi"]
- Explanation
- TextEditor textEditor = new TextEditor(); // The current text is "|". (The '|' character represents the cursor)
Python solution
class TextEditor:
def __init__(self):
self.left = []
self.right = []
def addText(self, text: str) -> None:
self.left.extend(list(text))
def deleteText(self, k: int) -> int:
k = min(k, len(self.left))
for _ in range(k):
self.left.pop()
return k
def cursorLeft(self, k: int) -> str:
k = min(k, len(self.left))
for _ in range(k):
self.right.append(self.left.pop())
return ''.join(self.left[-10:])
def cursorRight(self, k: int) -> str:
k = min(k, len(self.right))
for _ in range(k):
self.left.append(self.right.pop())
return ''.join(self.left[-10:])
# Your TextEditor object will be instantiated and called as such:
# obj = TextEditor()
# obj.addText(text)
# param_2 = obj.deleteText(k)
# param_3 = obj.cursorLeft(k)
# param_4 = obj.cursorRight(k)Complexity
- Time
- O(|text|)
- Space · auxiliary
- O(n)
Pattern: Linked List
Rewire pointers in place, with a dummy head and a saved next to keep it safe. LeetCode 2296. Design a Text Editor is filed here because LeetCode tags it Linked List and Doubly-Linked List, which is the vocabulary this hub collects.
The linked list guide has the Python template for the pattern and the 75 LeetCode problems that use it.
Related problems
| No. | Problem | Difficulty |
|---|---|---|
| 1472 | Design Browser History | Medium |
| 0844 | Backspace String Compare | Easy |
| 1910 | Remove All Occurrences of a Substring | Medium |
| 2211 | Count Collisions on a Road | Medium |
| 2390 | Removing Stars From a String | Medium |
| 2696 | Minimum String Length After Removing Substrings | Easy |
Frequently asked questions
- How hard is LeetCode 2296. Design a Text Editor?
LeetCode 2296. Design a Text Editor is rated Hard on LeetCode.
- What is the time complexity of LeetCode 2296. Design a Text Editor?
The Python solution on this page runs in O(|text|).
- What is the space complexity of LeetCode 2296. Design a Text Editor?
The Python solution on this page uses O(n) auxiliary space.
- What topics does LeetCode 2296. Design a Text Editor cover?
LeetCode 2296. Design a Text Editor is tagged Stack, Design, Linked List, String, Doubly-Linked List and Simulation on LeetCode.