Welcome to Subscribe On Youtube

Formatted question description: https://leetcode.ca/all/2296.html

2296. Design a Text Editor

  • Difficulty: Hard.
  • Related Topics: Linked List, String, Stack, Design, Simulation, Doubly-Linked List.
  • Similar Questions: .

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).

  • 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.

  Example 1:

Input
["TextEditor", "addText", "deleteText", "addText", "cursorRight", "cursorLeft", "deleteText", "cursorLeft", "cursorRight"]
[[], ["leetcode"], [4], ["practice"], [3], [8], [10], [2], [6]]
Output
[null, null, 4, null, "etpractice", "leet", 4, "", "practi"]

Explanation
TextEditor textEditor = new TextEditor(); // The current text is "|". (The '|' character represents the cursor)
textEditor.addText("leetcode"); // The current text is "leetcode|".
textEditor.deleteText(4); // return 4
                          // The current text is "leet|". 
                          // 4 characters were deleted.
textEditor.addText("practice"); // The current text is "leetpractice|". 
textEditor.cursorRight(3); // return "etpractice"
                           // The current text is "leetpractice|". 
                           // The cursor cannot be moved beyond the actual text and thus did not move.
                           // "etpractice" is the last 10 characters to the left of the cursor.
textEditor.cursorLeft(8); // return "leet"
                          // The current text is "leet|practice".
                          // "leet" is the last min(10, 4) = 4 characters to the left of the cursor.
textEditor.deleteText(10); // return 4
                           // The current text is "|practice".
                           // Only 4 characters were deleted.
textEditor.cursorLeft(2); // return ""
                          // The current text is "|practice".
                          // The cursor cannot be moved beyond the actual text and thus did not move. 
                          // "" is the last min(10, 0) = 0 characters to the left of the cursor.
textEditor.cursorRight(6); // return "practi"
                           // The current text is "practi|ce".
                           // "practi" is the last min(10, 6) = 6 characters to the left of the cursor.

  Constraints:

  • 1 <= text.length, k <= 40

  • text consists of lowercase English letters.

  • At most 2 * 104 calls in total will be made to addText, deleteText, cursorLeft and cursorRight.

  Follow-up: Could you find a solution with time complexity of O(k) per call?

Solution

  • class TextEditor {
        private final StringBuilder sb;
        private int cursor;
    
        public TextEditor() {
            sb = new StringBuilder();
            cursor = 0;
        }
    
        public void addText(String text) {
            sb.insert(cursor, text);
            cursor += text.length();
        }
    
        public int deleteText(int k) {
            int prevPos = cursor;
            if (cursor - k >= 0) {
                cursor -= k;
                sb.delete(cursor, cursor + k);
            } else {
                sb.delete(0, cursor);
                cursor = 0;
            }
            return prevPos - cursor;
        }
    
        public String cursorLeft(int k) {
            cursor = Math.max(cursor - k, 0);
            return sb.substring(Math.max(cursor - 10, 0), cursor);
        }
    
        public String cursorRight(int k) {
            cursor = Math.min(cursor + k, sb.length());
            return sb.substring(Math.max(cursor - 10, 0), cursor);
        }
    }
    
    /**
     * Your TextEditor object will be instantiated and called as such:
     * TextEditor obj = new TextEditor();
     * obj.addText(text);
     * int param_2 = obj.deleteText(k);
     * String param_3 = obj.cursorLeft(k);
     * String param_4 = obj.cursorRight(k);
     */
    
    ############
    
    class TextEditor {
        private StringBuilder left = new StringBuilder();
        private StringBuilder right = new StringBuilder();
    
        public TextEditor() {
        }
    
        public void addText(String text) {
            left.append(text);
        }
    
        public int deleteText(int k) {
            k = Math.min(k, left.length());
            left.setLength(left.length() - k);
            return k;
        }
    
        public String cursorLeft(int k) {
            k = Math.min(k, left.length());
            for (int i = 0; i < k; ++i) {
                right.append(left.charAt(left.length() - 1));
                left.deleteCharAt(left.length() - 1);
            }
            return left.substring(Math.max(left.length() - 10, 0));
        }
    
        public String cursorRight(int k) {
            k = Math.min(k, right.length());
            for (int i = 0; i < k; ++i) {
                left.append(right.charAt(right.length() - 1));
                right.deleteCharAt(right.length() - 1);
            }
            return left.substring(Math.max(left.length() - 10, 0));
        }
    }
    
    /**
     * Your TextEditor object will be instantiated and called as such:
     * TextEditor obj = new TextEditor();
     * obj.addText(text);
     * int param_2 = obj.deleteText(k);
     * String param_3 = obj.cursorLeft(k);
     * String param_4 = obj.cursorRight(k);
     */
    
  • 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)
    
    ############
    
    # 2296. Design a Text Editor
    # https://leetcode.com/problems/design-a-text-editor/
    
    class TextEditor:
    
        def __init__(self):
            self.A = ""
            self.cursor = 0
            self.N = 0
    
        def addText(self, text: str) -> None:
            p = self.N - self.cursor
            self.N += len(text)
            
            self.A = self.A[:p] + text + self.A[p:]
    
        def deleteText(self, k: int) -> int:
            p = self.N - self.cursor
            to_delete = min(k, p)
            
            self.A = self.A[:p - to_delete] + self.A[p:]
            
            self.N = len(self.A)
    
            return to_delete
    
        def cursorLeft(self, k: int) -> str:
            self.cursor = min(self.N, self.cursor + k)
    
            res = []
            n = min(10, self.N - self.cursor)
            
            for i in range(self.N - self.cursor - 1, -1, -1):
                res.append(self.A[i])
                
                if len(res) == n:
                    break
            
            return "".join(res[::-1])
    
        def cursorRight(self, k: int) -> str:
            self.cursor = max(0, self.cursor - k)
            
            res = []
            n = min(10, self.N - self.cursor)
            
            for i in range(self.N - self.cursor - 1, -1, -1):
                res.append(self.A[i])
                
                if len(res) == n:
                    break
            
            return "".join(res[::-1])
    
    
    # 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)
    
    
  • class TextEditor {
    public:
        TextEditor() {
        }
    
        void addText(string text) {
            left += text;
        }
    
        int deleteText(int k) {
            k = min(k, (int) left.size());
            left.resize(left.size() - k);
            return k;
        }
    
        string cursorLeft(int k) {
            k = min(k, (int) left.size());
            while (k--) {
                right += left.back();
                left.pop_back();
            }
            return left.substr(max(0, (int) left.size() - 10));
        }
    
        string cursorRight(int k) {
            k = min(k, (int) right.size());
            while (k--) {
                left += right.back();
                right.pop_back();
            }
            return left.substr(max(0, (int) left.size() - 10));
        }
    
    private:
        string left, right;
    };
    
    /**
     * Your TextEditor object will be instantiated and called as such:
     * TextEditor* obj = new TextEditor();
     * obj->addText(text);
     * int param_2 = obj->deleteText(k);
     * string param_3 = obj->cursorLeft(k);
     * string param_4 = obj->cursorRight(k);
     */
    
  • type TextEditor struct {
    	left, right []byte
    }
    
    func Constructor() TextEditor {
    	return TextEditor{}
    }
    
    func (this *TextEditor) AddText(text string) {
    	this.left = append(this.left, text...)
    }
    
    func (this *TextEditor) DeleteText(k int) int {
    	k = min(k, len(this.left))
    	if k < len(this.left) {
    		this.left = this.left[:len(this.left)-k]
    	} else {
    		this.left = []byte{}
    	}
    	return k
    }
    
    func (this *TextEditor) CursorLeft(k int) string {
    	k = min(k, len(this.left))
    	for ; k > 0; k-- {
    		this.right = append(this.right, this.left[len(this.left)-1])
    		this.left = this.left[:len(this.left)-1]
    	}
    	return string(this.left[max(len(this.left)-10, 0):])
    }
    
    func (this *TextEditor) CursorRight(k int) string {
    	k = min(k, len(this.right))
    	for ; k > 0; k-- {
    		this.left = append(this.left, this.right[len(this.right)-1])
    		this.right = this.right[:len(this.right)-1]
    	}
    	return string(this.left[max(len(this.left)-10, 0):])
    }
    
    func max(a, b int) int {
    	if a > b {
    		return a
    	}
    	return b
    }
    
    func min(a, b int) int {
    	if a < b {
    		return a
    	}
    	return b
    }
    
    /**
     * Your TextEditor object will be instantiated and called as such:
     * obj := Constructor();
     * obj.AddText(text);
     * param_2 := obj.DeleteText(k);
     * param_3 := obj.CursorLeft(k);
     * param_4 := obj.CursorRight(k);
     */
    

Explain:

nope.

Complexity:

  • Time complexity : O(n).
  • Space complexity : O(n).

All Problems

All Solutions