1. Brute Force — Array Storage & Value Rewriting
Intuition
Collect odd-indexed values in one array and even-indexed values in another. Concatenate the two arrays and write values back to the list.
Algorithm
- Step 1: Traverse list, append odd indexed values to
odds, even toevens. - Step 2: Combine:
combined = odds + evens. - Step 3: Traverse list again, assigning
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* oddEvenList(ListNode* head) { if (!head || !head->next) return head; vector<int> odds, evens; int idx = 1; for (ListNode* c = head; c; c = c->next, idx++) { if (idx % 2 == 1) odds.push_back(c->val); else evens.push_back(c->val); } ListNode* curr = head; for (int v : odds) { curr->val = v; curr = curr->next; } for (int v : evens) { curr->val = v; curr = curr->next; } return head; }}; 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* res = sol.oddEvenList(h); cout << "Brute Force Odd-Even: "; for (ListNode* c = res; c; c = c->next) cout << c->val << (c->next ? " -> " : ""); cout << endl; return 0;}Time & Space Complexity
- Time complexity:
O(N)— Collects N values into arrays and writes them back in two passes. - Space complexity:
O(N)— Allocates arrays of size N.
Why Brute Force Doesn't Scale:
Array allocations violate the O(1) space constraint and cause unnecessary heap allocations.
For N = 100,000 nodes, the in-place unzipping runs in <1ms with 0 extra memory.