Merge Two Insertion Diffs
Jane StreetOnsiteMedium
An insertion diff is a list of [position, value] pairs, sorted by position, with no position repeated. Applying a diff to a document places each value at index position of the result; the document's own elements keep their relative order and occupy the remaining indexes from left to right. For example, applying [[0, "a"], [3, "b"]] to ["x", "y", "z"] produces ["a", "x", "y", "b", "z"].
The document is not part of the input and may be very long, so it cannot be built explicitly. diff_one is applied first. The positions in diff_two are indices in the document after both diffs have been applied, i.e. final positions.
Part 1: Merge two diffs
Given two insertion diffs diff_one and diff_two, return one insertion diff that, applied by itself to the original document, produces the document that results from applying diff_one followed by diff_two.
The returned diff holds every insertion from both diffs as [position, value] pairs in increasing position order, where each position is the index the value ends up at in the final document. If a diff_two insertion and a diff_one insertion land on the same final position, the diff_two insertion comes first.
Merging must take time proportional to the total number of insertions alone; it may not depend on the document length or on how large the positions are.
- Example 1
- diff_one
[[0,"a"],[3,"b"]]- diff_two
[[0,"c"],[4,"d"]]- Output
[[0,"c"],[1,"a"],[4,"d"],[5,"b"]]
Why: After
diff_one,asits at index 0 andbat index 3.diff_twoputscat final index 0 anddat final index 4.ctakes index 0 and pushesato 1;canddboth land at or beforeb, pushing it to 5.
Constraints
0 <= len(diff_one) <= 10^50 <= len(diff_two) <= 10^50 <= diff_one[i][0] <= 10^9 + 10^50 <= diff_two[i][0] <= 10^9 + 10^5diff_one[i][0] < diff_one[i+1][0]diff_two[i][0] < diff_two[i+1][0]1 <= len(diff_one[i][1]) <= 51 <= len(diff_two[i][1]) <= 5- each
diff_one[i][0]is a valid index of the original document - each
diff_two[i][0]is a valid index of the document afterdiff_oneis applied