Apply Sequential Document Line Edits
Medium · Coding & Algorithms · Software Engineer · Onsite
Problem Statement
Simulate a text buffer organized as an ordered sequence of lines (document: List[str]) as a stream of edit operations (events: List[Dict[str, object]]) arrives one by one.
Implement process_document_edit_events(document, events):
def process_document_edit_events(
document: List[str], events: List[Dict[str, object]]
) -> List[str]:
Without modifying the caller's document list, execute each dictionary in events from first to last against the active buffer state, where every dictionary matches one of two schemas:
{"type": "insert_line", "index": i, "text": s}: Places stringsinto 0-based sloti(0 <= i <= L, whereLis the current line count right before this operation). Slot0prepends ahead of all existing lines, slotLappends after the final line, and any lines formerly at indicesi .. L - 1shift one position higher. RaiseValueErrorififalls outside0 .. L.{"type": "delete_document"}: Empties the active buffer completely ([]). Clearing an already-empty buffer leaves it empty, and anyinsert_lineoperations that follow start populating a fresh buffer from slot0.
Return the resulting list of lines after all operations in events have run.
Examples
Example 1
Input:
document = ["header", "footer"]
events = [
{"type": "insert_line", "index": 1, "text": "body"},
{"type": "insert_line", "index": 3, "text": "signature"}
]
Output: ["header", "body", "footer", "signature"]
Walk-through:
- Inserting "body" at slot 1 places it between "header" and "footer", producing ["header", "body", "footer"] (length 3).
- Inserting "signature" at slot 3 appends to the end, producing ["header", "body", "footer", "signature"].
Example 2
Input:
document = ["draft_1", "draft_2", "draft_3"]
events = [
{"type": "delete_document"},
{"type": "insert_line", "index": 0, "text": "intro"},
{"type": "insert_line", "index": 1, "text": "summary"}
]
Output: ["intro", "summary"]
Walk-through:
- delete_document wipes all three initial lines ([]).
- Subsequent insertions build a brand-new buffer: "intro" at slot 0 gives ["intro"], and "summary" at slot 1 gives ["intro", "summary"].
Example 3
Input:
document = []
events = [
{"type": "insert_line", "index": 0, "text": "beta"},
{"type": "insert_line", "index": 0, "text": "alpha"},
{"type": "insert_line", "index": 2, "text": "delta"},
{"type": "insert_line", "index": 2, "text": "gamma"}
]
Output: ["alpha", "beta", "gamma", "delta"]
Walk-through:
- Starting from [], "beta" enters slot 0 (["beta"]), "alpha" prepends at slot 0 (["alpha", "beta"]), "delta" appends at slot 2 (["alpha", "beta", "delta"]), and "gamma" inserts at slot 2 right before "delta" (["alpha", "beta", "gamma", "delta"]).
Example 4
Input:
document = ["notes", "todo"]
events = [
{"type": "insert_line", "index": 0, "text": "urgent"},
{"type": "delete_document"},
{"type": "delete_document"}
]
Output: []
Walk-through:
- "urgent" prepends to make ["urgent", "notes", "todo"]; the first delete_document empties the buffer to [], and the second delete_document leaves it [].
Constraints
0 <= len(document) <= 10,0000 <= len(events) <= 10,000- Every line string in
documentand"text"may be empty ("") or contain arbitrary characters, and duplicate line strings are allowed. - For every valid
"insert_line"operation,0 <= index <= LwhereLis the active buffer's current length (ValueErrorif out of bounds or if"type"is unknown).
Step-by-step walkthrough
Understand the document state and the two event types
Our document is a list of strings, where each string represents one line. We receive an initial
documentand a chronological list ofevents, and we return the final list of lines after applying every event in order.The easiest way to picture
insert_lineis to think of indices0throughlen(lines)as the gaps before, between, and after the current lines:Current lines : ["header", "footer"] (len = 2) Line positions: 0 1 Insert gaps : ^ ^ ^ index 0 index 1 index 2 (= len, appends at the end)With that picture in mind, both event types have simple rules:
{"type": "insert_line", "index": i, "text": s}placessinto gapi(0 <= i <= len(lines)), shifting any lines atior later one slot to the right.{"type": "delete_document"}removes every line so the document becomes[](where only gap0exists until new lines are inserted).
Copy the input list so we never mutate the caller's document
In Python, lists are passed by object reference. If we called
document.insert(...)ordocument.clear()directly on the input parameter, we would overwrite the caller's list as a side effect.Making a shallow copy at the start gives us our own working list:
lines = list(document)Because Python
strobjects are immutable (their characters can never be changed in place), a shallow list copylist(document)completely isolates our editor state from the caller inO(len(document))time.Process each event in chronological order
For each event dictionary in
events, we inspectevent["type"]and updatelines:- Why check
index < 0 or index > len(lines)explicitly? Python's built-inlist.insert(index, value)never raisesIndexError: a negative index counts backward from the end (-1inserts before the last line), and an index larger thanlen(lines)silently clamps to the end. Checking bounds explicitly catches bugs right away. - Why no
is_deletedboolean flag? Afterdelete_document, the document is simply empty ([]). Callinglines.clear()resets the state cleanly so both repeateddelete_documentevents and subsequentinsert_lineevents work with zero special cases.
for event in events: event_type = event["type"] if event_type == "insert_line": index = int(event["index"]) text = str(event["text"]) # Valid insert gaps are 0..len(lines) inclusive (index == len(lines) appends). # Guard explicitly because Python's list.insert silently wraps negative indices # and clamps oversized indices instead of raising an error. if index < 0 or index > len(lines): raise ValueError(f"insert index {index} out of range 0..{len(lines)}") lines.insert(index, text) elif event_type == "delete_document": # Wipe all existing lines; any later insert_line starts fresh from index 0. lines.clear() else: raise ValueError(f"unknown event type: {event_type!r}")- Why check
Check boundary states and resets
Let's verify how
linesbehaves across tricky state transitions:- Empty buffer insertion: When
linesis[],len(lines)is0, soindex = 0satisfies0 <= 0 <= 0and[].insert(0, s)produces[s]. - Front vs. tail slots:
index = 0places the new string ahead of every existing line;index = len(lines)places it right after the final line. - Back-to-back
delete_documentcalls: Calling[].clear()on an already-empty list is a harmless no-op that keepslinesequal to[]. - Rebuilding after a wipe: Once
lines.clear()empties the buffer, laterinsert_linecalls populate a fresh list starting fromindex = 0.
- Empty buffer insertion: When
Trace Example 2 and Example 3 step by step
Here is how
linesevolves across every event in Example 2 and Example 3:Example 2 — initial document = ["draft_1", "draft_2", "draft_3"]: start -> lines = ["draft_1", "draft_2", "draft_3"] (valid gaps: 0..3) 1. delete_document -> lines = [] (valid gaps: 0..0) 2. insert_line(0, "intro") -> lines = ["intro"] (valid gaps: 0..1) 3. insert_line(1, "summary") -> lines = ["intro", "summary"] (valid gaps: 0..2) Result: ["intro", "summary"] Example 3 — initial document = []: start -> lines = [] (valid gaps: 0..0) 1. insert_line(0, "beta") -> lines = ["beta"] (valid gaps: 0..1) 2. insert_line(0, "alpha") -> lines = ["alpha", "beta"] (valid gaps: 0..2) 3. insert_line(2, "delta") -> lines = ["alpha", "beta", "delta"] (valid gaps: 0..3) 4. insert_line(2, "gamma") -> lines = ["alpha", "beta", "gamma", "delta"] Result: ["alpha", "beta", "gamma", "delta"]Complete solution
Putting the copy, the event loop, and the defensive checks into
process_document_edit_events:from typing import Any, Dict, List, Optional, Set, Tuple def process_document_edit_events( document: List[str], events: List[Dict[str, object]], ) -> List[str]: # lines: working copy of current document lines, e.g. ["header", "footer"]. # Copying up front keeps the caller's original list untouched. lines: List[str] = list(document) # Replay every edit in chronological order against the current state of lines. for event in events: event_type = event["type"] if event_type == "insert_line": index = int(event["index"]) text = str(event["text"]) # Valid insert gaps are 0..len(lines) inclusive (index == len(lines) appends). # Guard explicitly because Python's list.insert silently wraps negative indices # and clamps oversized indices instead of raising an error. if index < 0 or index > len(lines): raise ValueError(f"insert index {index} out of range 0..{len(lines)}") lines.insert(index, text) elif event_type == "delete_document": # Wipe all existing lines; any later insert_line starts fresh from index 0. lines.clear() else: raise ValueError(f"unknown event type: {event_type!r}") return lines✅ Submit now — all tests should pass.
Intuition & how it works
Picture the document as a vertical column of paper strips on your desk, one strip per line. An insert_line event slides a new strip into one of the len(lines) + 1 gaps — gap 0 sits above the first line, gap i sits right before line i, and gap len(lines) sits below the last line — while delete_document sweeps the entire desk clean so the next edit starts on a blank surface.
Two naive habits trip candidates up here. First, mutating document directly with document.insert(...) or document.clear() silently corrupts the caller's input list; second, rebuilding the list via slicing (lines = lines[:i] + [text] + lines[i:]) copies every line on every single event, even when appending at the end. Working on a single copied list lines = list(document) and applying lines.insert(index, text) and lines.clear() in place keeps the state transitions straightforward and bug-free.
Walk through Example 2 starting from document = ["draft_1", "draft_2", "draft_3"]:
1. Copy document into lines = ["draft_1", "draft_2", "draft_3"].
2. {"type": "delete_document"} clears lines to [].
3. {"type": "insert_line", "index": 0, "text": "intro"} inserts into gap 0 of [], giving ["intro"].
4. {"type": "insert_line", "index": 1, "text": "summary"} inserts into gap 1 (len(lines)), appending "summary" to return ["intro", "summary"].
Complexity
Let D be len(document), E be len(events), and M be the maximum number of lines the document holds at any point (M <= D + E).
- Time: O(D + E * M) in the worst case. Copying the initial list takes
O(D). Inserting at the end (index == len(lines)) takes amortized O(1) time (meaningO(1)on average per append, because Python occasionally resizes the underlying array by a constant factor), whereas inserting near the front shifts up toMline references and takesO(M). Across the whole run,lines.clear()drops each inserted or initial line at most once, contributingO(D + E)total work. - Space: O(D + E) auxiliary space in the worst case to hold the
lineslist of string references (the immutable string contents themselves are shared withdocumentandevents, not duplicated).
Edge cases
- Empty initial document and empty
events: Returns a fresh[]. - Inserting into an empty document:
index = 0equalslen(lines), which cleanly produces[text]. - Inserting at index
0vs indexlen(lines): Both boundary gaps are valid (0prepends,len(lines)appends). - Consecutive
delete_documentevents: Clearing an already-empty list is a safe no-op. - Inserts after
delete_document: Only edits after the finaldelete_documentsurvive in the returned list. - Empty strings (
"") and duplicate lines: Treated like any other line string without losing their positions. - Caller's input list preservation:
lines = list(document)ensures the caller'sdocumentlist is never mutated.
Common mistakes
- Mutating
documentin place instead of copyinglines = list(document)first. - Off-by-one check on
index == len(lines): Rejectingindex == len(lines)makes it impossible to insert into an empty document or append at the end. - Relying on
list.insertto catch bad indices: Python'slist.insert(-1, s)silently inserts before the last element instead of raising, so explicit0 <= index <= len(lines)validation is safer. - Tracking a sticky
deleted = Trueflag that accidentally blocks or alters validinsert_lineevents arriving afterdelete_document.
Alternative approaches
- Jump straight to the last
delete_document: If every event ineventsis guaranteed to be valid, anydelete_documentwipes bothdocumentand all earlier edits. You can scaneventsbackward to find the index of the finaldelete_document; if one exists, start fromlines = []and replay only the suffix of events after it, avoiding wastedO(M)shifts before the wipe. (The trade-off is that skipping earlier events also skips validating them if malformed inputs are possible.)
Follow-up questions
- How would you keep line insertions fast if a document grew to millions of lines with frequent edits near the top? On a million-line array,
list.insert(0, text)shifts a million pointers (O(M)per edit). You can reduce both lookup by line number and insertion toO(log M)using a rope (a balanced binary tree of line chunks where each node stores the total line count in its subtree so you can binary-search to lineias you descend). Real text editors also use a gap buffer (a flat array with an empty movable gap at the cursor so nearby inserts areO(1)) or a piece table (an append-only buffer of added text paired with a sequence of span descriptors pointing into the original and added buffers). - How would you extend this design to support undo and redo commands? Maintain an
undo_stackof inverse commands and clear theredo_stackwhenever a fresh edit arrives. Undoinginsert_line(i, text)pops linei(lines.pop(i)), while undoingdelete_documentrestores the previous list of lines — ifdelete_documentsaves the oldlinesreference ontoundo_stackand assignslines = [](instead of mutating it with.clear()), bothdelete_documentand its undo run inO(1)time! - What goes wrong when two clients submit line-index edits concurrently over a network, and how do collaborative editors resolve it? Raw line indices go stale whenever edits cross in flight: if Alice inserts at line
5at the same moment Bob inserts at line0, Alice's edit actually belongs at line6once Bob's arrives. Collaborative editors solve this either with operational transformation (OT) (a server-sequenced algorithm that shifts an incoming edit's index past concurrent edits it had not yet seen) or a CRDT (Conflict-free Replicated Data Type) (a data structure that assigns every line a unique fractional position ID plus a replica tie-breaker so replicas converge to the exact same line order without a central coordinator).
Follow-up questions
- How would you keep line insertions fast if a document grew to millions of lines with frequent edits near the top?
- How would you extend this design to support undo and redo commands?
- What goes wrong when two clients submit line-index edits concurrently over a network, and how do collaborative editors resolve it?
Similar questions
- Design a Weekly Top-Comments Email Digest
- 2D Max Pooling with Source Coordinates
- Time-Limited Credit Ledger
- Grid Path Scoring with Streak Bonuses
- Place One Hub to Minimize Maximum Grid Distance
- Increment Fixed-Size Digit Array by One