Imagine you have a linked list like a chain of connected nodes, where each node contains a unique integer value. You're also given an array nums that contains some of these values (but not necessarily all of them).
Your task is to find how many connected components exist in the linked list for the values in nums. Two values form a connected component if they appear consecutively in the linked list and both values are present in the nums array.
Example: If your linked list is 0→1→2→3 and nums = [0, 1, 3], then:
- Values 0 and 1 are consecutive and both in nums → 1 component
- Value 3 is in nums but not connected to others → 1 component
- Total: 2 components
Return the total number of connected components.
Input & Output
Visualization
Time & Space Complexity
n nodes to traverse + m elements to build hash set, each lookup is O(1)
Hash set stores m elements from nums array
Constraints
- The number of nodes in the linked list is in the range [1, 104]
- 0 ≤ Node.val < 104
- All values in the linked list are unique
- 1 ≤ nums.length ≤ 104
- 0 ≤ nums[i] < 104
- All values in nums are unique
- nums is a subset of all values in the linked list