Skip to content
LC-0817 Medium LeetCode

817. Linked List Components

Read the full problem statement on LeetCode.
Difficulty: medium Acceptance: 57% Topics: Array, Hash Table, Linked List
View full problem on LeetCode
Reference solution (spoiler · python)
# Time:  O(m + n), m is the number of G, n is the number of nodes
# Space: O(m)

class ListNode(object):
    def __init__(self, x):
        self.val = x
        self.next = None


class Solution(object):
    def numComponents(self, head, G):
        """
        :type head: ListNode
        :type G: List[int]
        :rtype: int
        """
        lookup = set(G)
        dummy = ListNode(-1)
        dummy.next = head
        curr = dummy
        result = 0
        while curr and curr.next:
            if curr.val not in lookup and curr.next.val in lookup:
                result += 1
            curr = curr.next
        return result

Solution from kamyu104/LeetCode-Solutions · MIT