Skip to content

817. Linked List Components 👎

  • Time: $O(n)$
  • Space: $O(n)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
class Solution {
 public:
  int numComponents(ListNode* head, vector<int>& nums) {
    int ans = 0;
    unordered_set<int> setNums{nums.begin(), nums.end()};

    for (; head; head = head->next)
      if (setNums.contains(head->val) &&
          (!head->next || !setNums.contains(head->next->val)))
        ++ans;

    return ans;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
class Solution {
  public int numComponents(ListNode head, int[] nums) {
    int ans = 0;
    Set<Integer> setNums = new HashSet<>();

    for (final int g : nums)
      setNums.add(g);

    for (; head != null; head = head.next)
      if (setNums.contains(head.val) && (head.next == null || !setNums.contains(head.next.val)))
        ++ans;

    return ans;
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
class Solution:
  def numComponents(self, head: ListNode | None, nums: list[int]) -> int:
    ans = 0
    numsSet = set(nums)

    while head:
      if head.val in numsSet and (
              head.next == None or head.next.val not in numsSet):
        ans += 1
      head = head.next

    return ans