1. Brute Force — Extract to Array, Sort & Overwrite
Intuition
Read all node values into an array, sort the array, and traverse the list again to overwrite each node's val.
Algorithm
- Step 1: Traverse list and push all node values into array
vals. - Step 2: Sort
valsin ascending order. - Step 3: Traverse list again, setting
curr.val = vals[i]. - Step 4: Return original
head.
#include <iostream>#include <vector>#include <algorithm> using namespace std; struct ListNode { int val; ListNode *next; ListNode(int x) : val(x), next(nullptr) {}}; class Solution {public: ListNode* insertionSortList(ListNode* head) { if (!head) return nullptr; vector<int> vals; for (ListNode* curr = head; curr; curr = curr->next) { vals.push_back(curr->val); } sort(vals.begin(), vals.end()); int i = 0; for (ListNode* curr = head; curr; curr = curr->next) { curr->val = vals[i++]; } return head; }}; int main() { ListNode* h = new ListNode(4); h->next = new ListNode(2); h->next->next = new ListNode(1); h->next->next->next = new ListNode(3); Solution sol; ListNode* sorted = sol.insertionSortList(h); cout << "Brute Force Sorted: "; for (ListNode* c = sorted; c; c = c->next) cout << c->val << (c->next ? " -> " : ""); cout << endl; return 0;}Time & Space Complexity
- Time complexity:
O(N log N)— Extracts N values in O(N), sorts array in O(N log N), rewrites values in O(N). - Space complexity:
O(N)— Allocates array buffer of size N.
Why Brute Force Doesn't Scale:
For reverse-sorted lists of size N, total comparisons equal N*(N-1)/2, which becomes slow for N > 50,000.
For N = 5,000, O(N2) takes ~12.5M operations (~10ms). For general O(N log N) sorting, prefer Merge Sort (sort-list).