Resolve Overlapping Text Edit Spans by Priority
Greedy & IntervalsAuto-graded · 17 test casesLast updated
Sweep over span boundaries with a heap to resolve overlapping inclusive edit spans using priority, original length, and input order, splitting losers into fragments.
Resolve Overlapping Text Edit Spans by Priority
You are given a list of edit records for a piece of text. Each record is a dictionary with these keys:
start(int): first index covered, inclusiveend(int): last index covered, inclusivepriority(int): a larger number means a stronger editchange(string): the kind of edit, for example"DELETE","DEDUP","UPDATE","UPPERCASE"or"LOWERCASE"
Records may overlap. Produce a list of records that do not overlap, in which every index is assigned to exactly one winning record, determined as follows.
Choosing the winner at an index
If several records cover the same index, the winner is picked by these rules, in order:
- The record with the larger
prioritywins. - If priorities are equal, the record with the smaller original length
end - startwins. - If still tied, the record that appears earlier in the input list wins.
Splitting
A record that loses on only part of its range is cut into the pieces on which it still wins. Every piece is a separate output record that carries the same priority, change and any other fields as the original record, with only start and end changed.
The rules above always use the original record's priority, length and input position, even for a piece. For example, if (1, 10) is split into (1, 2) and (7, 10), both pieces are still treated as having length 10 - 1 = 9 when compared with anything else.
Output
Return the output records sorted by start. The output must be minimal:
- Indices covered by no input record produce no output.
- Two consecutive output records are merged into one if they come from the same original record and are directly adjacent (the second starts at the first's
end + 1). Adjacent records that come from different input records are never merged, even if all their fields are equal. - Every output record keeps all fields of its source record (including any extra keys), with
startandendreplaced by the piece's bounds.
The input can be large, so the solution must not loop over every individual index.
Constraints
0 <= len(corrections); the list may be empty, in which case return[].start <= endfor every record; a record withstart == endcovers a single index.- Indices and priorities are integers and may be large in magnitude.
- The input list must not be relied upon to be sorted.
- The time limit expects roughly
O(n log n)behavior.
Examples
Example 1
Input: resolve_edit_spans([{'start': 1, 'end': 10, 'priority': 1, 'change': 'UPPERCASE'}, {'start': 3, 'end': 6, 'priority': 1, 'change': 'LOWERCASE'}])
Output: [{'start': 1, 'end': 2, 'priority': 1, 'change': 'UPPERCASE'}, {'start': 3, 'end': 6, 'priority': 1, 'change': 'LOWERCASE'}, {'start': 7, 'end': 10, 'priority': 1, 'change': 'UPPERCASE'}]
Example 2
Input: resolve_edit_spans([{'start': 0, 'end': 4, 'priority': 1, 'change': 'DELETE'}, {'start': 2, 'end': 6, 'priority': 3, 'change': 'UPDATE'}])
Output: [{'start': 0, 'end': 1, 'priority': 1, 'change': 'DELETE'}, {'start': 2, 'end': 6, 'priority': 3, 'change': 'UPDATE'}]
Example 3
Input: resolve_edit_spans([{'start': 5, 'end': 8, 'priority': 2, 'change': 'UPPERCASE'}, {'start': 5, 'end': 8, 'priority': 2, 'change': 'LOWERCASE'}])
Output: [{'start': 5, 'end': 8, 'priority': 2, 'change': 'UPPERCASE'}]
Hints
Hint 1
The winner at an index can only change at a record's start or just after its end (end + 1). Collect those boundary points and sort them.
Hint 2
Between two consecutive boundary points the set of covering records is constant, so one record wins the whole stretch. Keep the active records in a heap keyed by (-priority, end - start, input_index), computed once from the original record.
Hint 3
Remove expired records lazily when they reach the top of the heap (end is less than the current point). To keep output minimal, extend the previous output piece when the same record wins a directly adjacent stretch, and reset that state across gaps.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The winner at an index depends only on which records cover it, and that set changes only at a record's start (it becomes active) or at its end + 1 (it stops being active). So:
- Collect all boundary points (every
startand everyend + 1) and sort them. Each pair of consecutive points[p, q)is an elementary segment with a constant set of covering records, hence a constant winner. There are at most2nsuch segments. - Sweep the points left to right. At each point
p, push every record starting atponto a min-heap keyed by(-priority, end - start, input_index). This key encodes all three tie-break rules directly. - Pop expired records from the top of the heap (those with
end < p). Records buried deeper can stay until they surface, since they cannot affect the top. - If the heap is empty, the segment is a gap: emit nothing and reset the "previous winner" state. Otherwise the heap top is the winner for
[p, q - 1]. - If the winner is the same record as the last emitted piece and that piece ended exactly at
p - 1, extend the last piece. Otherwise emit a new copy of the winner withstartandendreplaced.
Why it is correct
- Between consecutive boundary points the covering set is fixed, so the winner is fixed.
- Every record with
start <= phas been pushed and every expired record that could be on top has been removed, so the heap top is the true best under the rules. - The key is computed once from the original record, and pieces are never re-inserted, so split pieces automatically keep their original priority, length and input order.
- Merging is based on record identity (its input index), not field equality, so adjacent pieces from different records stay separate while contiguous pieces of the same record are joined. This gives the minimal output, and emission order makes it sorted.
Complexity
- Time:
O(n log n)for sorting up to2npoints plus at most one push and one pop per record. - Space:
O(n)for the points, start map, heap and output.
Reference solution
import heapq
from typing import List, Dict
def resolve_edit_spans(edits: List[Dict]) -> List[Dict]:
if not edits:
return []
starts = {}
for i, e in enumerate(edits):
starts.setdefault(e["start"], []).append(i)
points = set(starts)
for e in edits:
points.add(e["end"] + 1)
points = sorted(points)
heap = []
result = []
prev_winner = None
prev_end = None
for pos, nxt in zip(points, points[1:]):
for i in starts.get(pos, []):
e = edits[i]
heapq.heappush(heap, (-e["priority"], e["end"] - e["start"], i))
while heap and edits[heap[0][2]]["end"] < pos:
heapq.heappop(heap)
if not heap:
prev_winner = None
prev_end = None
continue
winner = heap[0][2]
if winner == prev_winner and prev_end == pos:
result[-1]["end"] = nxt - 1
else:
out = dict(edits[winner])
out["start"] = pos
out["end"] = nxt - 1
result.append(out)
prev_winner = winner
prev_end = nxt
return result