#2296
Hard Algorithms Design a text editor
Linked List String Stack Design Simulation Doubly-Linked List
50.1% acceptance
Feb 23, 2026
651
228
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).
Move the cursor either left or right.
When deleting text, only characters to the left of the cursor will be deleted. The cursor will also remain within the actual text and cannot be moved beyond it. More formally, we have that 0 <= cursor.position <= currentText.length always holds.
Implement the TextEditor class:
TextEditor() Initializes the object with empty text.
void addText(string text) Appends text to where the cursor is. The cursor ends to the right of text.
int deleteText(int k) Deletes k characters to the left of the cursor. Returns the number of characters actually deleted.
string cursorLeft(int k) Moves the cursor to the left k times. Returns the last min(10, len) characters to the left of the cursor, where len is the number of characters to the left of the cursor.
string cursorRight(int k) Moves the cursor to the right k times. Returns the last min(10, len) characters to the left of the cursor, where len is the number of characters to the left of the cursor.
Solution
Rust
Time O(2^n)
Space O(n)
pub struct TextEditor {
left: Vec<u8>,
right: Vec<u8>,
}
impl TextEditor {
pub fn new() -> Self {
TextEditor { left: Vec::new(), right: Vec::new() }
}
pub fn add_text(&mut self, text: String) {
for b in text.bytes() {
self.left.push(b);
}
}
pub fn delete_text(&mut self, k: i32) -> i32 {
let k = (k as usize).min(self.left.len());
self.left.truncate(self.left.len() - k);
k as i32
}
pub fn cursor_left(&mut self, k: i32) -> String {
let k = (k as usize).min(self.left.len());
for _ in 0..k {
let b = self.left.pop().unwrap();
self.right.push(b);
}
self.get_left_str()
}
pub fn cursor_right(&mut self, k: i32) -> String {
let k = (k as usize).min(self.right.len());
for _ in 0..k {
let b = self.right.pop().unwrap();
self.left.push(b);
}
self.get_left_str()
}
fn get_left_str(&self) -> String {
let len = self.left.len().min(10);
let start = self.left.len() - len;
String::from_utf8(self.left[start..].to_vec()).unwrap()
}
}