Leetcode 817. Linked List Components
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. The task is to return the number of connected components in the linked list that are formed by the nodes from nums
.
A connected component of the linked list is a subset of nodes such that:
nums
.[1, 10^4]
.1 <= Node.val <= 10^4
1 <= nums.length <= 10^4
nums
values are unique.nums
is a subset of values in the linked list.nums
in a set for O(1) average-time complexity look-up.Here’s the Java code to accomplish this:
import java.util.HashSet;
import java.util.Set;
public class Solution {
public int numComponents(ListNode head, int[] nums) {
Set<Integer> numSet = new HashSet<>();
// Add all elements of nums into the set
for (int num : nums) {
numSet.add(num);
}
int components = 0;
boolean inComponent = false;
// Traverse the linked list
ListNode current = head;
while (current != null) {
if (numSet.contains(current.val)) {
if (!inComponent) {
// We found the start of a new component
components++;
inComponent = true;
}
} else {
// End of the current component
inComponent = false;
}
current = current.next;
}
return components;
}
}
nums
: O(N) where N is the length of nums
.Thus, the overall time complexity is O(N + L).
nums
in the set.Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?