1597. Reversed Referral Copy
A referral chain stores members in the order they joined. Each member node has a val, a next link and a random link that points to the member who referred them, or is null. You are given the head of such a chain.
Build a completely new chain, sharing no node with the original, whose next order is the exact reverse of the original order. Every new node keeps the value of its original, and its random must point to the new node that copies the original node's random target (null stays null; a node may point to itself). Return the head of the new chain, or null if head is null. The original chain must be left untouched. Aim for O(n) time and O(n) extra space with a hash map from original node to copy.
Example 1
- Input:
- head = [[7,null],[13,0],[11,2],[10,0]]
- Output:
- [[10,3],[11,1],[13,3],[7,null]]
- Explanation:
The copy reads 10, 11, 13, 7; the copy of 10 points to the copy of 7, which is now last.
Example 2
- Input:
- head = [[1,1],[2,null]]
- Output:
- [[2,null],[1,0]]
- Explanation:
The reversed copy is 2 then 1, and the copy of 1 points to the copy of 2, which is its predecessor.
Constraints
0 ≤ length ≤ 1000. Node values fit in a 32-bit signed integer. 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)