Collapse Adjacent Edits Before Applying Them to a Text Buffer
Stacks & QueuesAuto-graded · 21 test casesLast updated
Simulate a queue of insert and format edits, merging adjacent inserts and dropping repeated adjacent formats, then return the final text and ordered list of applied styles.
Edit Queue Compaction
A text editor keeps a buffer that starts with some initial text. A queue of edits is applied to it in order. Before applying anything, the editor compacts the queue to remove redundant work.
Each edit is one of two kinds:
"insert": appends the given string to the end of the buffer text."format": records that the given style name (for example"BOLD") was applied.
The edits are supplied as two parallel lists. operations[i] is the kind of the i-th edit, and arguments[i] is a list whose first element is that edit's string argument (the text to insert, or the style name).
Compaction rules
Process the edits from left to right, comparing each incoming edit with the last edit that has been kept so far (not the raw previous input):
- If an
insertarrives and the last kept edit is also aninsert, merge them into one insert whose text is the concatenation of the two (earlier text first). - If a
formatarrives and the last kept edit is aformatwith exactly the same style string (case-sensitive), discard the incoming one. - Otherwise, keep the edit as a new entry.
Because comparison is against the last kept edit, chains collapse fully: three inserts in a row become one, and three identical formats in a row become one. Identical formats that are separated by any other kept edit (including an insert of an empty string) are not adjacent and are both kept.
Applying the compacted queue
Apply the kept edits in order, starting from initial_text:
- an
insertappends its text to the buffer; - a
formatappends its style to a list of applied styles.
Task
Return a dictionary with two keys:
"text": the final buffer text,"formats": the list of applied styles, in the order they were applied.
Special cases
- If an operation name is neither
"insert"nor"format", raiseValueError. - If
operationsandargumentshave different lengths, only the firstmin(len)pairs are considered. - With no edits, return
initial_textand an empty list. - The input lists must not be modified.
Constraints
- Up to 10,000 edits.
- Each
arguments[i]contains at least one string; only its first element is used. initial_text, inserted texts and style names are strings (they may be empty).- Edit order must never be rearranged.
Examples
Example 1
Input: compact_and_apply_edits('Hello', ['insert', 'format', 'format', 'insert'], [[' World'], ['BOLD'], ['BOLD'], ['!']])
Output: {'text': 'Hello World!', 'formats': ['BOLD']}
Example 2
Input: compact_and_apply_edits('', ['insert', 'insert', 'format'], [['a'], ['b'], ['ITALIC']])
Output: {'text': 'ab', 'formats': ['ITALIC']}
Example 3
Input: compact_and_apply_edits('Draft', ['format', 'format', 'format', 'insert'], [['BOLD'], ['ITALIC'], ['BOLD'], ['!']])
Output: {'text': 'Draft!', 'formats': ['BOLD', 'ITALIC', 'BOLD']}
Hints
Hint 1
Scan the edits once, keeping a list of retained edits; only the last retained edit matters for each decision.
Hint 2
Compare the incoming edit with the last retained edit, not with the previous raw input. This makes runs of three or more collapse correctly.
Hint 3
Equal formats separated by an insert (even an empty one) are not adjacent. After compaction, run through the kept edits to build the text and the style list.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The work splits into two phases.
1. Compaction. Walk through the edits once from left to right, maintaining a list of kept edits that acts like a stack. For each incoming edit, look only at the top of that list:
- Incoming
insertand top is aninsert: append the new text to the top's text. - Incoming
formatand top is aformatwith the same style: skip it. - Anything else: push it as a new entry.
- Any other operation name raises
ValueError.
2. Application. Go through the kept edits in order. Inserts extend the text starting from initial_text, and formats are appended to the style list. Return both.
Why it is correct
- Order is never changed. An edit is only ever merged into, or dropped relative to, the edit directly before it in the kept list.
- Appending
aand thenbgives the same text as appendinga + b, so merging inserts does not change the result. - Comparing against the top of the kept list, instead of the raw previous input, means runs of any length collapse:
insert, insert, insertbecomes one insert andBOLD, BOLD, BOLDbecomes oneBOLD. - Only directly adjacent duplicates are removed. In
BOLD, insert, BOLDthe insert sits between the two formats, so both stay, matching the rules exactly. An empty insert still counts as an insert and separates formats. zipstops at the shorter list, which gives the required behavior for mismatched lengths, and the input lists are never modified.
Complexity
- Time: O(n + L), where n is the number of edits and L is the total length of text handled. Each edit is processed once. Repeated string concatenation inside a merge can cost more in the worst case, but CPython usually handles in-place appends well, and a list of pieces joined once removes the concern if needed.
- Space: O(n + L) for the kept list and the resulting text.
Reference solution
from typing import Dict, List
def compact_and_apply_edits(initial_text: str, operations: List[str], arguments: List[List[str]]) -> Dict[str, object]:
kept = [] # each entry: [kind, value]
for name, args in zip(operations, arguments):
if name == "insert":
if kept and kept[-1][0] == "insert":
kept[-1][1] += args[0]
else:
kept.append(["insert", args[0]])
elif name == "format":
if kept and kept[-1][0] == "format" and kept[-1][1] == args[0]:
continue
kept.append(["format", args[0]])
else:
raise ValueError("unknown operation")
text = initial_text
formats = []
for kind, value in kept:
if kind == "insert":
text += value
else:
formats.append(value)
return {"text": text, "formats": formats}