Leetcode 817. Linked List Components
We are given the head of a linked list and an array nums that is a subset of the elements in the linked list. The goal is to determine the number of connected components in the linked list that are formed by the elements in nums.
nums array?
[1, 10^4].nums will be in the range [1, 10^4].nums into a set to allow O(1) average time complexity for checking membership.nums.Here’s how you can implement this strategy in C++:
#include <unordered_set>
// 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) {}
};
class Solution {
public:
int numComponents(ListNode* head, std::vector<int>& nums) {
// Create a set of nums for efficient lookup
std::unordered_set<int> numSet(nums.begin(), nums.end());
ListNode* current = head;
int componentCount = 0;
bool inComponent = false;
// Traverse the linked list
while (current != nullptr) {
// Check if current node is in nums
if (numSet.find(current->val) != numSet.end()) {
// If we're not already in a component, we've found a new component
if (!inComponent) {
componentCount++;
inComponent = true;
}
} else {
// If current node is not in nums, we're not in a component
inComponent = false;
}
current = current->next;
}
return componentCount;
}
};
nums.nums requires O(n) space.Thus, this approach is efficient and well-suited for the problem constraints.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?