1. Brute Force — Array Storage & Value Overwrite
Intuition
Read all node values into two separate arrays: < x and >= x. Combine the arrays and overwrite node values.
Algorithm
- Step 1: Traverse list, adding values
< xtoless, and>= xtogreater. - Step 2: Combine
combined = less + greater. - Step 3: Traverse list again, setting
curr.val = combined[i]. - Step 4: Return
head.
#include <iostream>#include <vector> using namespace std; struct ListNode { int val; ListNode *next; ListNode(int x) : val(x), next(nullptr) {}}; class Solution {public: ListNode* partition(ListNode* head, int x) { if (!head || !head->next) return head; vector<int> less, greater; for (ListNode* c = head; c; c = c->next) { if (c->val < x) less.push_back(c->val); else greater.push_back(c->val); } ListNode* curr = head; for (int v : less) { curr->val = v; curr = curr->next; } for (int v : greater) { curr->val = v; curr = curr->next; } return head; }}; int main() { ListNode* h = new ListNode(1); h->next = new ListNode(4); h->next->next = new ListNode(3); h->next->next->next = new ListNode(2); h->next->next->next->next = new ListNode(5); h->next->next->next->next->next = new ListNode(2); Solution sol; ListNode* res = sol.partition(h, 3); cout << "Brute Force Partition: "; for (ListNode* c = res; c; c = c->next) cout << c->val << (c->next ? " -> " : ""); cout << endl; return 0;}Time & Space Complexity
- Time complexity:
O(N)— Extracts N values in O(N), partitions in O(N), writes back in O(N). - Space complexity:
O(N)— Allocates array buffer of size N.
Why Brute Force Doesn't Scale:
Array allocations violate the O(1) space requirement and duplicate node values.
For N = 100,000 nodes, dual sentinel partitioning executes in <1ms with 0 heap bytes allocated.