1581. Sorted Chain Union

Easy1.5 points estimatedLinked ListTwo Pointers

Two clubs keep their member ID lists in non-decreasing order, and the organisers want one combined roll without repeats. Given the heads a and b of two non-decreasing singly linked lists, return a new list that contains every distinct value appearing in either list exactly once, in strictly increasing order. Duplicates inside a single list also collapse to one node. If both inputs are empty, return null. Walk both lists together with two pointers, remembering the last value written, so the work is O(n + m) time with O(1) extra space apart from the output list.

Example 1

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

The distinct values across both lists are 1, 2, 3, 7 and 8, listed once each in increasing order.

Example 2

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

Only the value 4 appears, so the result is a single node.

Example 3

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

One list is empty, so the result is the other list with duplicates removed.

Constraints

0 ≤ length of a, length of b ≤ 1000

Both lists are 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)

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…