1. Brute Force — Frequency Hash Map & List Reconstruction
Intuition
Count the frequency of each value in a hash map. Build a new linked list containing only values with frequency == 1.
Algorithm
- Step 1: Traverse list and populate frequency map
freq[node.val]++. - Step 2: Create
dummy = new ListNode(0)andtail = dummy. - Step 3: Traverse list again: if
freq[node.val] == 1, create new node and append totail. - Step 4: Return
dummy.next.
#include <iostream>#include <unordered_map> using namespace std; struct ListNode { int val; ListNode *next; ListNode(int x) : val(x), next(nullptr) {}}; class Solution {public: ListNode* deleteDuplicates(ListNode* head) { unordered_map<int, int> freq; for (ListNode* c = head; c; c = c->next) freq[c->val]++; ListNode* dummy = new ListNode(0); ListNode* tail = dummy; for (ListNode* c = head; c; c = c->next) { if (freq[c->val] == 1) { tail->next = new ListNode(c->val); tail = tail->next; } } ListNode* res = dummy->next; delete dummy; return res; }}; int main() { ListNode* h = new ListNode(1); h->next = new ListNode(2); h->next->next = new ListNode(3); h->next->next->next = new ListNode(3); h->next->next->next->next = new ListNode(4); h->next->next->next->next->next = new ListNode(4); h->next->next->next->next->next->next = new ListNode(5); Solution sol; ListNode* res = sol.deleteDuplicates(h); cout << "Brute Force Deduplicated II: "; for (ListNode* c = res; c; c = c->next) cout << c->val << (c->next ? " -> " : ""); cout << endl; return 0;}Time & Space Complexity
- Time complexity:
O(N)— Pass 1 counts frequencies in O(N). Pass 2 constructs new list of unique elements in O(N). - Space complexity:
O(N)— Allocates a hash map of unique values and new nodes.
Why Brute Force Doesn't Scale:
Hash maps use O(N) extra space and cause memory fragmentation.
For N = 100,000 nodes, in-place lookahead bypass completes in <0.6ms.