Leetcode 835 Solution

This article provides solution to leetcode question 835 (linked-list-components)

https://leetcode.com/problems/linked-list-components

Solution

# Definition for singly-linked list.
# 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
        """
        pos = {}
        i = 0

        while head:
            pos[head.val] = i
            i += 1
            head = head.next

        bm = [0] * i
        for x in G:
            bm[pos[x]] = 1

        ans = 0
        for i in range(len(bm)):
            if bm[i] == 1 and (i == 0 or bm[i - 1] == 0):
                ans += 1

        return ans