1275. Sorted Union Merge

Easy1.5 points estimatedTwo PointersArraySorting

Two libraries each keep a sorted catalogue of book codes. A catalogue is stored in non-decreasing order and may list the same code several times because of duplicate copies. The libraries are merging, and the new shared catalogue should list every code that appears in a or in b exactly once.

Return the shared catalogue as an array of distinct values in ascending order. Either input may be empty, in which case the answer is built from the other one, and if both are empty the answer is an empty array. Use one pointer per array, always taking the smaller current value, and skip a value if it equals the last one written. Aim for O(a.length + b.length) time.

Example 1

Input:
a = [1,1,3], b = [1,2,3,3]
Output:
[1,2,3]
Explanation:

The values present are 1, 2 and 3, listed once each in ascending order.

Example 2

Input:
a = [], b = [5,5]
Output:
[5]
Explanation:

The first catalogue is empty and the second only holds 5, so the result is [5].

Constraints

0 ≤ a.length, b.length ≤ 200

-109 ≤ a[i], b[i] ≤ 109

a and b are each sorted in non-decreasing order

How this problem is judged

Answers
Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.

Expected complexity

Time
O(n + m)
Space
O(1) extra

What the author was aiming for. Your own solution is not measured against it.

Asked in an interview

Were you asked this in an interview? Say where, anonymously.

Code
Loading the editor…