1. Brute Force — Array Storage & Direct Index Lookup
Intuition
Read all node pointers into an array. Access index length / 2 in O(1) time.
Algorithm
- Step 1: Create an array
nodes = []. - Step 2: Traverse
curr = head, pushingcurrtonodes. - Step 3: Return
nodes[nodes.length / 2].
#include <iostream>#include <vector> using namespace std; struct ListNode { int val; ListNode *next; ListNode(int x) : val(x), next(nullptr) {}}; class Solution {public: ListNode* middleNode(ListNode* head) { vector<ListNode*> nodes; while (head) { nodes.push_back(head); head = head->next; } return nodes[nodes.size() / 2]; }}; int main() { ListNode* h = new ListNode(1); h->next = new ListNode(2); h->next->next = new ListNode(3); h->next->next->next = new ListNode(4); h->next->next->next->next = new ListNode(5); Solution sol; ListNode* mid = sol.middleNode(h); cout << "Brute Force Middle: " << (mid ? mid->val : -1) << endl; return 0;}Time & Space Complexity
- Time complexity:
O(N)— Traverses the list of N nodes and inserts into an array in O(N). - Space complexity:
O(N)— Allocates array buffer storing N node pointers.
Why Brute Force Doesn't Scale:
Storing all nodes in an array incurs O(N) memory allocation.
For N = 1,000,000 nodes, fast/slow pointer traversal finishes in ~2ms with 0 bytes extra heap.