You are given the head
of a linked list containing unique integer values and an integer array nums
that is a subset of the linked list values.
Return the number of connected components in nums
where two values are connected if they appear consecutively in the linked list.
Example 1:
Input: head = [0,1,2,3], nums = [0,1,3] Output: 2 Explanation: 0 and 1 are connected, so [0, 1] and [3] are the two connected components.
Example 2:
Input: head = [0,1,2,3,4], nums = [0,3,1,4] Output: 2 Explanation: 0 and 1 are connected, 3 and 4 are connected, so [0, 1] and [3, 4] are the two connected components.
Constraints:
n
.1 <= n <= 104
0 <= Node.val < n
Node.val
are unique.1 <= nums.length <= n
0 <= nums[i] < n
nums
are unique.This problem asks to find the number of connected components in a subset (nums
) of values from a linked list. Two values are considered connected if they appear consecutively in the linked list.
The solution uses a HashSet (or a set in Python) to efficiently check if a value is present in nums
. The algorithm iterates through the linked list. It counts a connected component whenever it encounters a node whose value is in nums
and it wasn't already in a connected component.
Algorithm:
Create a HashSet: Create a HashSet s
containing all the values from the input array nums
. This allows for O(1) lookup time to check if a node's value is in nums
.
Iterate the Linked List: Iterate through the linked list using a while
loop.
Skip Non-members: Skip nodes whose values are not in s
.
Count Components: When a node with a value in s
is found, increment the component count (ans
). Then, continue iterating until a node whose value is not in s
is encountered.
Time Complexity: O(N), where N is the number of nodes in the linked list. We iterate through the linked list at most once. HashSet operations (insertion and lookup) take O(1) on average.
Space Complexity: O(M), where M is the length of the nums
array. This is the space used to store the HashSet s
.
Code Explanation (Python):
class Solution:
def numComponents(self, head: Optional[ListNode], nums: List[int]) -> int:
ans = 0 # Initialize the component count
s = set(nums) # Create a set from nums for efficient lookups
while head: # Iterate through the linked list
while head and head.val not in s: # Skip nodes not in nums
head = head.next
ans += head is not None # Increment count if a node in nums is found
while head and head.val in s: # Skip nodes in nums that are part of the current component
head = head.next
return ans
The code in other languages follows a very similar structure, using their respective set implementations and syntax. The core logic remains the same.