Linked List Components

medium linked-list hashing

Problem

Given the head of a linked list with unique values and a list nums (a subset of the values), return the number of connected components in nums where two values are connected iff they are adjacent in the list.

Inputhead = [0,1,2,3], nums = [0,1,3]
Output2
{0,1} is one component, {3} is another.

def numComponents(head, nums):
    s = set(nums)
    cnt = 0
    cur = head
    while cur:
        if cur.val in s and (cur.next is None or cur.next.val not in s):
            cnt += 1
        cur = cur.next
    return cnt
var numComponents = function(head, nums) {
    const s = new Set(nums);
    let cnt = 0, cur = head;
    while (cur) {
        if (s.has(cur.val) && (cur.next === null || !s.has(cur.next.val))) cnt++;
        cur = cur.next;
    }
    return cnt;
};
class Solution {
    public int numComponents(ListNode head, int[] nums) {
        java.util.Set<Integer> s = new java.util.HashSet<>();
        for (int x : nums) s.add(x);
        int cnt = 0;
        ListNode cur = head;
        while (cur != null) {
            if (s.contains(cur.val) && (cur.next == null || !s.contains(cur.next.val))) cnt++;
            cur = cur.next;
        }
        return cnt;
    }
}
class Solution {
public:
    int numComponents(ListNode* head, vector<int>& nums) {
        unordered_set<int> s(nums.begin(), nums.end());
        int cnt = 0;
        ListNode* cur = head;
        while (cur) {
            if (s.count(cur->val) && (cur->next == nullptr || !s.count(cur->next->val))) cnt++;
            cur = cur->next;
        }
        return cnt;
    }
};
Time: O(n + m) Space: O(m)