1598. Filtered Referral Copy

Medium3.5 points estimatedLinked ListHash Table

A referral chain has nodes with a val, a next link and a random link to some node of the same chain (or null). Given the head and an integer threshold, produce a brand new chain that contains a fresh copy of every node whose value is at least threshold, in the original relative order. Nodes with smaller values are dropped.

For a kept node, the copy's random must point to the copy of its original target when that target was also kept; if the target was dropped or the original random is null, the copy's random is null. Return the head of the new chain (null when nothing is kept) and do not modify the original nodes. Target O(n) time and O(n) space using a hash map from original nodes to copies.

Example 1

Input:
head = [[5,2],[1,0],[8,null],[3,1]], threshold = 4
Output:
[[5,1],[8,null]]
Explanation:

Only 5 and 8 survive; the copy of 5 points to the copy of 8, and 8 has no random.

Example 2

Input:
head = [[2,1],[9,0],[4,1]], threshold = 3
Output:
[[9,null],[4,0]]
Explanation:

2 is dropped, so the copy of 9 gets a null random while the copy of 4 points to the copy of 9.

Constraints

0 ≤ length ≤ 1000; -104 ≤ val, threshold ≤ 104. Each random pointer is null or targets a node of the same list.

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)
Space
O(n)

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…