Design a Text Editor — LeetCode 2296 Python Solution
HardStackDesignLinked ListStringDoubly-Linked ListSimulation
- Problem
- #2296
- Pattern
- Linked List
- 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
Python
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
| Measure | Complexity |
|---|---|
| Time | O(|\text{text}|) |
| Space | O(n) auxiliary |
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
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{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.