Linked List Components — LeetCode 817 Python Solution

MediumArrayHash TableLinked List
Problem
#817
Reading time
3 min

The problem

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

Input
head = [0,1,2,3], nums = [0,1,3]
Output
2
Explanation
0 and 1 are connected, so [0, 1] and [3] are the two connected components.

Python solution

Python
# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution:
    def numComponents(self, head: Optional[ListNode], nums: List[int]) -> int:
        ans = 0
        s = set(nums)
        while head:
            while head and head.val not in s:
                head = head.next
            ans += head is not None
            while head and head.val in s:
                head = head.next
        return ans

Complexity

MeasureComplexity
TimeO(n)
SpaceO(n) auxiliary

Pattern: Linked List

Rewire pointers in place, with a dummy head and a saved next to keep it safe. LeetCode 817. Linked List Components is filed here because LeetCode tags it Linked List, which is the vocabulary this hub collects.

The linked list guide has the Python template for the pattern and the 75 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 817. Linked List Components?
LeetCode 817. Linked List Components is rated Medium on LeetCode.
What is the time complexity of LeetCode 817. Linked List Components?
The Python solution on this page runs in O(n).
What is the space complexity of LeetCode 817. Linked List Components?
The Python solution on this page uses O(n) auxiliary space.
What topics does LeetCode 817. Linked List Components cover?
LeetCode 817. Linked List Components is tagged Array, Hash Table and Linked List on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview