1. Brute Force — Hash Set Node Address Lookup
Intuition
Record every node pointer from list A in a hash set. Walk list B and return the first node pointer that is present in the set.
Algorithm
- Step 1: Create an empty
HashSetof node pointers. - Step 2: Traverse
currAfromheadA, adding each node address to the set. - Step 3: Traverse
currBfromheadB. Ifset.contains(currB), returncurrB. - Step 4: If end of list B is reached without a match, return
null.
#include <iostream>#include <unordered_set> using namespace std; struct ListNode { int val; ListNode *next; ListNode(int x) : val(x), next(nullptr) {}}; class Solution {public: ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) { unordered_set<ListNode*> visited; ListNode* currA = headA; while (currA) { visited.insert(currA); currA = currA->next; } ListNode* currB = headB; while (currB) { if (visited.count(currB)) { return currB; } currB = currB->next; } return nullptr; }}; int main() { ListNode* c1 = new ListNode(8); ListNode* c2 = new ListNode(4); ListNode* c3 = new ListNode(5); c1->next = c2; c2->next = c3; ListNode* a1 = new ListNode(4); ListNode* a2 = new ListNode(1); a1->next = a2; a2->next = c1; ListNode* b1 = new ListNode(5); ListNode* b2 = new ListNode(6); ListNode* b3 = new ListNode(1); b1->next = b2; b2->next = b3; b3->next = c1; Solution sol; ListNode* inter = sol.getIntersectionNode(a1, b1); cout << "Brute Force Intersection: " << (inter ? to_string(inter->val) : "null") << endl; return 0;}Time & Space Complexity
- Time complexity:
O(N + M)— Inserts all N nodes of list A into a hash set in O(N), then queries for M nodes of list B in O(M). - Space complexity:
O(N)— Stores N node references in the hash table.
Why Brute Force Doesn't Scale:
Hash set stores N references, incurring hash table allocation overhead.
For N = 30,000 and M = 30,000, two pointers use 0 extra bytes and complete in <0.5ms.