#440 · Classes · Expert · 210 XP · about 40 min
You are building the core of a text editor that must stay fast on a document of millions of characters. The editor holds a text and a cursor, which sits between two characters or at either end. Build a TextEditor class:
TextEditor() starts with an empty text and the cursor at the start.add_text(text) inserts text at the cursor; the cursor ends up right after the inserted text.delete(k) deletes up to k characters to the left of the cursor (fewer if the cursor is closer to the start than that).left(k) moves the cursor up to k places to the left, stopping at the start of the text.right(k) moves the cursor up to k places to the right, stopping at the end of the text.Every method returns the characters to the left of the cursor after the call, but at most the last 10 of them: the 10 characters that sit right before the cursor, or fewer when the cursor is near the start.
ed = TextEditor() ed.add_text('hello world') # returns 'ello world' ed.left(6) # returns 'hello' ed.delete(2) # returns 'hel' ed.add_text('p') # returns 'help' ed.right(100) # returns 'help world' ed.left(100) # returns ''
delete removes, at most 2,000,000 characters (a huge k stops at the end of the text)s[:cursor] + text + s[cursor:], is far too slow for a text this long.First solves only, ranked by stars and then time.