1. Brute Force — Array Extraction & BigInt Addition
Intuition
Extract all node values into big integers or digit arrays, perform arithmetic addition, and convert the resulting sum back into a singly linked list.
Algorithm
- Step 1: Traverse list l1, collecting digits into a string or BigInt.
- Step 2: Traverse list l2, collecting digits into a second string or BigInt.
- Step 3: Reverse both strings and compute
sum = BigInt(str1) + BigInt(str2). - Step 4: Convert the sum back to string, reverse it, and construct a new linked list node by node.
#include <iostream>#include <vector>#include <string>#include <algorithm> using namespace std; struct ListNode { int val; ListNode* next; ListNode(int x) : val(x), next(nullptr) {}}; class Solution {public: ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) { vector<int> n1, n2; while (l1) { n1.push_back(l1->val); l1 = l1->next; } while (l2) { n2.push_back(l2->val); l2 = l2->next; } vector<int> res; int carry = 0, i = 0, j = 0; while (i < n1.size() || j < n2.size() || carry) { int sum = carry; if (i < n1.size()) sum += n1[i++]; if (j < n2.size()) sum += n2[j++]; carry = sum / 10; res.push_back(sum % 10); } ListNode dummy(0); ListNode* curr = &dummy; for (int v : res) { curr->next = new ListNode(v); curr = curr->next; } return dummy.next; }}; int main() { ListNode* l1 = new ListNode(2); l1->next = new ListNode(4); l1->next->next = new ListNode(3); ListNode* l2 = new ListNode(5); l2->next = new ListNode(6); l2->next->next = new ListNode(4); Solution sol; ListNode* res = sol.addTwoNumbers(l1, l2); cout << "Brute Force Output: "; while (res) { cout << res->val << (res->next ? " -> " : ""); res = res->next; } cout << endl; return 0;}Time & Space Complexity
- Time complexity:
O(N + M)— Extracting digits into strings/arrays and parsing requires O(N + M) time. - Space complexity:
O(N + M)— Intermediate strings or arrays store all N and M digits in memory.
Why Brute Force Doesn't Scale:
Converting linked lists to native numbers fails due to IEEE 754 floating point and 64-bit integer limits (overflows beyond 18 digits).
For two linked lists with 100,000 digits each, streaming digit-by-digit simulation processes addition in ~3ms with ~4MB RAM, whereas integer parsing crashes with integer overflow.