Jane Street questions

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.

  1. 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, a sits at index 0 and b at index 3. diff_two puts c at final index 0 and d at final index 4. c takes index 0 and pushes a to 1; c and d both land at or before b, pushing it to 5.

Constraints

  • 0 <= len(diff_one) <= 10^5
  • 0 <= len(diff_two) <= 10^5
  • 0 <= diff_one[i][0] <= 10^9 + 10^5
  • 0 <= diff_two[i][0] <= 10^9 + 10^5
  • diff_one[i][0] < diff_one[i+1][0]
  • diff_two[i][0] < diff_two[i+1][0]
  • 1 <= len(diff_one[i][1]) <= 5
  • 1 <= 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 after diff_one is applied
Import your own questions
Paste a question you were asked and get a full problem: statement, tests and a checked solution.
Import a question