#817

Linked List Components

Medium
ArrayHash TableLinked ListHash MapArray
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(n)
💡

Intuition

Time O(n)Space O(n)

The optimal solution uses a set to quickly check if a node's value is in nums and counts components based on consecutive nodes in the linked list.

⚙️

Algorithm

5 steps
  1. 1Step 1: Create a set from the nums array for O(1) lookups.
  2. 2Step 2: Initialize a count variable to zero.
  3. 3Step 3: Traverse the linked list, checking if each node's value is in the set.
  4. 4Step 4: If a value is found, increment the count and skip all consecutive nodes that are also in the set.
  5. 5Step 5: Return the count after traversing the entire linked list.
solution.py18 lines
1# Full working Python code
2class ListNode:
3    def __init__(self, val=0, next=None):
4        self.val = val
5        self.next = next
6
7def numComponents(head, nums):
8    nums_set = set(nums)
9    count = 0
10    current = head
11    while current:
12        if current.val in nums_set:
13            count += 1
14            while current and current.val in nums_set:
15                current = current.next
16        else:
17            current = current.next
18    return count

Complexity note: The time complexity is O(n) because we traverse the linked list once, and the space complexity is O(n) due to the set storing the nums values.

  • 1Using a set allows for O(1) lookups, which is crucial for performance.
  • 2Identifying consecutive components is key to solving the problem efficiently.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.