Linked List Components - 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.

A connected component is a maximal group of consecutive nodes whose values are all present in nums.

Input & Output

Example 1 — Basic Connected Components
$ Input: head = [0,1,2,3], nums = [0,1,3,2]
Output: 1
💡 Note: The linked list is 0→1→2→3. All values [0,1,2,3] are present in nums and appear consecutively in the linked list, forming one connected component.
Example 2 — Separate Components
$ Input: head = [0,1,2,3,4], nums = [0,3,1,4]
Output: 2
💡 Note: Linked list: 0→1→2→3→4. Node 0 is in nums (start component 1), node 1 is in nums (continue component 1), node 2 is not in nums (end component 1), node 3 is in nums (start component 2), node 4 is in nums (continue component 2). Result: 2 components.
Example 3 — Single Component
$ Input: head = [0,1,2,3,4], nums = [1,2,3]
Output: 1
💡 Note: Node 0 not in nums, nodes 1,2,3 are consecutive in nums forming one component, node 4 not in nums. Only one connected component.

Constraints

  • The number of nodes in the linked list is in the range [1, 104]
  • 0 ≤ Node.val < 104
  • All values in the linked list are unique
  • 1 ≤ nums.length ≤ 104
  • 0 ≤ nums[i] < 104
  • All values in nums are unique

Visualization

Tap to expand
Linked List Components INPUT Linked List: 0 1 2 3 nums array (subset): 0 1 3 2 HashSet from nums: {0, 1, 2, 3} Input Values: head = [0,1,2,3] nums = [0,1,3,2] All nums values in list ALGORITHM STEPS 1 Build HashSet Store nums in set for O(1) lookup 2 Traverse List Visit each node in order 3 Check Membership Is node value in HashSet? 4 Count Components New component when gap found Traversal Process: Component 1 0 --> 1 | gap Component 2 2 --> 3 0,1 consecutive in list AND in nums 2,3 consecutive in list AND in nums 1-->2 break: forms 2 components FINAL RESULT Connected Components Found: Component 1 0 1 Component 2 2 3 OUTPUT 2 OK - Verified 2 connected components Group 1: {0,1} Group 2: {2,3} Key Insight: Using a HashSet allows O(1) lookup to check if a node's value is in nums. A new component starts when we encounter a node in nums after a node NOT in nums (or at the beginning). Count increments only at the START of each connected run. Time: O(n), Space: O(m) where m = len(nums). TutorialsPoint - Linked List Components | Hash Set Optimization
Asked in
Facebook 3 Microsoft 2
23.4K Views
Medium Frequency
~15 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen