KatInterview

835. Linked List Components

MediumSolutions in Python, Java, C++, TypeScript

Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.

Approach

Method Explanation

This problem asks us to count the number of "connected components" from a subset of values nums within a linked list. A connected component is a maximal sequence of consecutive nodes in the linked list whose values are all present in nums.

Solution

Linked List Components in Python

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
from typing import List, Optional

class Solution:
    def numComponents(self, head: Optional[ListNode], nums: List[int]) -> int:
        # Step 1: Create a set for efficient O(1) average time lookups.
        num_set = set(nums)
        
        component_count = 0
        in_component = False # Flag to track if the previous node was in a component.
        current = head
        
        # Step 2: Traverse the linked list.
        while current:
            # Step 3: Check if the current node's value is in our set.
            if current.val in num_set:
                # If we find a value from nums and we were not previously in a component,
                # it means we have found the start of a new component.
                if not in_component:
                    component_count += 1
                    in_component = True # Mark that we are now inside a component.
            else:
                # If the value is not in nums, any component we were in has ended.
                in_component = False
            
            # Move to the next node.
            current = current.next
            
        return component_count

Linked List Components in Java

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode() {}
 *     ListNode(int val) { this.val = val; }
 *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */
import java.util.HashSet;
import java.util.Set;

class Solution {
    public int numComponents(ListNode head, int[] nums) {
        // Step 1: Create a hash set for efficient O(1) average time lookups.
        Set<Integer> numSet = new HashSet<>();
        for (int num : nums) {
            numSet.add(num);
        }
        
        int componentCount = 0;
        boolean inComponent = false; // Flag to track if the previous node was in a component.
        ListNode current = head;
        
        // Step 2: Traverse the linked list.
        while (current != null) {
            // Step 3: Check if the current node's value is in our set.
            if (numSet.contains(current.val)) {
                // If we find a value from nums and we were not previously in a component,
                // it means we have found the start of a new component.
                if (!inComponent) {
                    componentCount++;
                    inComponent = true; // Mark that we are now inside a component.
                }
            } else {
                // If the value is not in nums, any component we were in has ended.
                inComponent = false;
            }
            // Move to the next node.
            current = current.next;
        }
        
        return componentCount;
    }
}

Linked List Components in C++

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
#include <vector>
#include <unordered_set>

class Solution {
public:
    int numComponents(ListNode* head, std::vector<int>& nums) {
        // Step 1: Create a hash set for efficient O(1) average time lookups.
        std::unordered_set<int> num_set(nums.begin(), nums.end());
        
        int component_count = 0;
        bool in_component = false; // Flag to track if the previous node was in a component.
        ListNode* current = head;
        
        // Step 2: Traverse the linked list.
        while (current != nullptr) {
            // Step 3: Check if the current node's value is in our set.
            if (num_set.count(current->val)) {
                // If we find a value from nums and we were not previously in a component,
                // it means we have found the start of a new component.
                if (!in_component) {
                    component_count++;
                    in_component = true; // Mark that we are now inside a component.
                }
            } else {
                // If the value is not in nums, any component we were in has ended.
                in_component = false;
            }
            // Move to the next node.
            current = current->next;
        }
        
        return component_count;
    }
};

Linked List Components in TypeScript

/**
 * Definition for singly-linked list.
 * class ListNode {
 *     val: number
 *     next: ListNode | null
 *     constructor(val?: number, next?: ListNode | null) {
 *         this.val = (val===undefined ? 0 : val)
 *         this.next = (next===undefined ? null : next)
 *     }
 * }
 */

function numComponents(head: ListNode | null, nums: number[]): number {
    // Step 1: Create a Set for efficient O(1) average time lookups.
    const numSet = new Set(nums);
    
    let componentCount = 0;
    let inComponent = false; // Flag to track if the previous node was in a component.
    let current = head;
    
    // Step 2: Traverse the linked list.
    while (current) {
        // Step 3: Check if the current node's value is in our set.
        if (numSet.has(current.val)) {
            // If we find a value from nums and we were not previously in a component,
            // it means we have found the start of a new component.
            if (!inComponent) {
                componentCount++;
                inComponent = true; // Mark that we are now inside a component.
            }
        } else {
            // If the value is not in nums, any component we were in has ended.
            inComponent = false;
        }
        
        // Move to the next node.
        current = current.next;
    }
    
    return componentCount;
};

Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.

LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.