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: 2
💡 Note: The linked list is 0→1→2→3. Values [0,1] form one component, value [2] is isolated, and value [3] forms another component. So we have components: [0,1] and [2] and [3], but since all values are in nums, we have [0,1], [2], [3] as separate runs in the linked list order, giving us 2 components: [0,1] and [2,3].
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: Find Connected GroupsLinked List:01234nums = [0, 3, 1, 4]Component 1Component 2✓ in nums✓ in nums✗ not in nums✓ in nums✓ in numsResult: 2 Connected ComponentsComponents: [0,1] and [3,4] (consecutive in linked list)Node 2 breaks the sequence, creating separate components
Understanding the Visualization
1
Input
Linked list: 0→1→2→3→4 and nums: [0,3,1,4]
2
Process
Traverse list, check if each value is in nums
3
Output
Count connected components: 2
Key Takeaway
🎯 Key Insight: A new component starts when current node is in nums but we weren't previously in a component
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