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 string s into 0-based slot i (0 <= i <= L, where L is the current line count right before this operation). Slot 0 prepends ahead of all existing lines, slot L appends after the final line, and any lines formerly at indices i .. L - 1 shift one position higher. Raise ValueError if i falls outside 0 .. L.
  • {"type": "delete_document"}: Empties the active buffer completely ([]). Clearing an already-empty buffer leaves it empty, and any insert_line operations that follow start populating a fresh buffer from slot 0.

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,000
  • 0 <= len(events) <= 10,000
  • Every line string in document and "text" may be empty ("") or contain arbitrary characters, and duplicate line strings are allowed.
  • For every valid "insert_line" operation, 0 <= index <= L where L is the active buffer's current length (ValueError if out of bounds or if "type" is unknown).

Step-by-step walkthrough

  1. 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 document and a chronological list of events, and we return the final list of lines after applying every event in order.

    The easiest way to picture insert_line is to think of indices 0 through len(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} places s into gap i (0 <= i <= len(lines)), shifting any lines at i or later one slot to the right.
    • {"type": "delete_document"} removes every line so the document becomes [] (where only gap 0 exists until new lines are inserted).
  2. 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(...) or document.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 str objects are immutable (their characters can never be changed in place), a shallow list copy list(document) completely isolates our editor state from the caller in O(len(document)) time.

  3. Process each event in chronological order

    For each event dictionary in events, we inspect event["type"] and update lines:

    • Why check index < 0 or index > len(lines) explicitly? Python's built-in list.insert(index, value) never raises IndexError: a negative index counts backward from the end (-1 inserts before the last line), and an index larger than len(lines) silently clamps to the end. Checking bounds explicitly catches bugs right away.
    • Why no is_deleted boolean flag? After delete_document, the document is simply empty ([]). Calling lines.clear() resets the state cleanly so both repeated delete_document events and subsequent insert_line events 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}")
    
  4. Check boundary states and resets

    Let's verify how lines behaves across tricky state transitions:

    • Empty buffer insertion: When lines is [], len(lines) is 0, so index = 0 satisfies 0 <= 0 <= 0 and [].insert(0, s) produces [s].
    • Front vs. tail slots: index = 0 places the new string ahead of every existing line; index = len(lines) places it right after the final line.
    • Back-to-back delete_document calls: Calling [].clear() on an already-empty list is a harmless no-op that keeps lines equal to [].
    • Rebuilding after a wipe: Once lines.clear() empties the buffer, later insert_line calls populate a fresh list starting from index = 0.
  5. Trace Example 2 and Example 3 step by step

    Here is how lines evolves 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"]
    
  6. 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 (meaning O(1) on average per append, because Python occasionally resizes the underlying array by a constant factor), whereas inserting near the front shifts up to M line references and takes O(M). Across the whole run, lines.clear() drops each inserted or initial line at most once, contributing O(D + E) total work.
  • Space: O(D + E) auxiliary space in the worst case to hold the lines list of string references (the immutable string contents themselves are shared with document and events, not duplicated).

Edge cases

  • Empty initial document and empty events: Returns a fresh [].
  • Inserting into an empty document: index = 0 equals len(lines), which cleanly produces [text].
  • Inserting at index 0 vs index len(lines): Both boundary gaps are valid (0 prepends, len(lines) appends).
  • Consecutive delete_document events: Clearing an already-empty list is a safe no-op.
  • Inserts after delete_document: Only edits after the final delete_document survive 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's document list is never mutated.

Common mistakes

  • Mutating document in place instead of copying lines = list(document) first.
  • Off-by-one check on index == len(lines): Rejecting index == len(lines) makes it impossible to insert into an empty document or append at the end.
  • Relying on list.insert to catch bad indices: Python's list.insert(-1, s) silently inserts before the last element instead of raising, so explicit 0 <= index <= len(lines) validation is safer.
  • Tracking a sticky deleted = True flag that accidentally blocks or alters valid insert_line events arriving after delete_document.

Alternative approaches

  • Jump straight to the last delete_document: If every event in events is guaranteed to be valid, any delete_document wipes both document and all earlier edits. You can scan events backward to find the index of the final delete_document; if one exists, start from lines = [] and replay only the suffix of events after it, avoiding wasted O(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 to O(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 line i as you descend). Real text editors also use a gap buffer (a flat array with an empty movable gap at the cursor so nearby inserts are O(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_stack of inverse commands and clear the redo_stack whenever a fresh edit arrives. Undoing insert_line(i, text) pops line i (lines.pop(i)), while undoing delete_document restores the previous list of lines — if delete_document saves the old lines reference onto undo_stack and assigns lines = [] (instead of mutating it with .clear()), both delete_document and its undo run in O(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 5 at the same moment Bob inserts at line 0, Alice's edit actually belongs at line 6 once 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

Similar questions

More Clickup interview questions

All 2 Clickup questions →