1584. Random Pointer Hops
Each member of a referral network is a node in a linked list, and besides its next pointer every node carries a random pointer to any node of the same list, or to null. Starting at head, keep following random pointers. Return how many distinct nodes you visit, counting the head, before you either reach null or arrive at a node that was already visited. For an empty list return 0. The next pointers are irrelevant to the walk. Record visited nodes in a hash set, so the work is O(n) time and O(n) space.
Example 1
- Input:
- head = [[1,2],[2,0],[3,1]]
- Output:
- 3
- Explanation:
Hops go 1 -> 3 -> 2 -> 1; the head is revisited after three distinct nodes.
Example 2
- Input:
- head = [[5,null],[6,0]]
- Output:
- 1
- Explanation:
The head has no random pointer, so only the head is visited.
Example 3
- Input:
- head = []
- Output:
- 0
- Explanation:
An empty list has no nodes to visit.
Constraints
0 ≤ length ≤ 1000
Each random pointer is null or points to a node of the 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)