You get the head of a linked list whose node values are all different, and an array nums holding some of those values.
Mark every node whose value is in nums. A component is a run of marked nodes that sit next to each other in the list and cannot be stretched any further. Return how many components there are.
Example 1
Input: head = [3, 0, 4, 1, 2], nums = [3, 0, 1] Output: 2 Why: runs [3, 0] and [1]; node 4 breaks them apart
2 more examples and the constraints
Example 2
Input: head = [2, 4, 0, 1, 3], nums = [2, 4, 1, 3] Output: 2 Why: runs [2, 4] and [1, 3], split by node 0
Example 3
Input: head = [5, 1, 3, 0, 4, 2], nums = [5, 3, 4] Output: 3 Why: 5, 3 and 4 each stand alone
Constraints
- 1 ≤ n ≤ 10,000, where n is the number of nodes
- Node values are distinct and between 0 and n − 1
- 1 ≤ length of nums ≤ n, and its values are distinct values from the list
Your turn first
Have a go on paper or in your own editor, then reveal the approaches from the simplest up.
- Scan nums for each nodeO(n · m)
- Hash set + count endsO(n + m)
The idea in one sentence
The pattern, how to spot it, and the best complexity.
Side by side
| Approach | Time | Relative work for 10,000 nodes | Verdict |
|---|---|---|---|
| Scan nums for each node | O(n · m) | Correct, but slow | |
| Hash set + count ends | O(n + m) | Best; one walk |
n = nodes in the list, m = length of nums.
Edge cases to test
- Every node is wanted. The whole list is one component, so the answer is 1.
- A component at the very end. The last node has no next node; it still closes a component.
- No two wanted nodes touch. Each one is its own component, as in Example 3.
- A single node. head = [0], nums = [0] gives 1.
- Order of nums. nums is a set of values, not a path; its order does not matter.
Common mistakes
- Counting wanted nodes instead of runs of them.
- Forgetting the null check on the last node, which crashes or misses the final component.
- Assuming nums is in list order and walking the two side by side.
How to talk through it
- 1Clarify. Are values unique? Can nums be in any order? Is a single node a component?
- 2Define what you count. A component is counted at its last node: wanted, with an unwanted or missing next.
- 3Give the slow check. Scanning nums per node is O(n · m).
- 4Use a set. Turn nums into a hash set so each check is O(1), then walk once.
- 5Test out loud. Run all-wanted, a run at the tail and isolated nodes.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?