Zepruv › Coding problems

Linked List Components

Medium · Array, Hash Table, Linked List

You are given the head of a linked list containing unique integer values and an integer array nums that is a subset of the linked list values.
Return the number of connected components in nums where two values are connected if they appear consecutively in the linked list.

Example 1

Input: head = [0,1,2,3], nums = [0,1,3]
Output: 2

0 and 1 are connected, so [0, 1] and [3] are the two connected components.

Example 2

Input: head = [0,1,2,3,4], nums = [0,3,1,4]
Output: 2

0 and 1 are connected, 3 and 4 are connected, so [0, 1] and [3, 4] are the two connected components.

Constraints

Starter code (python)

# Definition for singly-linked list.
# class ListNode(object):
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution(object):
    def numComponents(self, head, nums):
        """
        :type head: Optional[ListNode]
        :type nums: List[int]
        :rtype: int
        """
        

Related problems

Previous: Ambiguous Coordinates · Next: Race Car · All problems

Zepruv is a technical interview practice platform. Read any problem for free; sign in to run your code, submit and keep your progress.