Skip to content

817. Linked List Components

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

js
/**
 * Definition for singly-linked list.
 * function ListNode(val) {
 *     this.val = val;
 *     this.next = null;
 * }
 */
/**
 * @param {ListNode} head
 * @param {number[]} G
 * @return {number}
 */
var numComponents = function(head, G) {
    let current = head
    let connected = 0
    let size = 0

    while (current) {
        if (G.indexOf(current.val) < 0) {
            if (size > 0) {
                connected += 1
                size = 0
            }
        } else {
            size += 1
        }
        current = current.next
    }

    if (size > 0) {
        connected += 1
    }

    return connected
};