1. Brute Force — In-Place Reversal & Forward Addition
Intuition
Reverse l1 and l2 to reduce the problem to Add Two Numbers I. Add them, and reverse the resulting list.
Algorithm
- Step 1: Write helper function to reverse a singly linked list.
- Step 2: Reverse l1 and l2 in-place.
- Step 3: Add the two reversed lists using elementary carry addition.
- Step 4: Reverse the result list and restore l1 and l2.
- Step 5: Return the reversed result head.
#include <iostream> using namespace std; struct ListNode { int val; ListNode* next; ListNode(int x) : val(x), next(nullptr) {}}; class Solution {private: ListNode* reverseList(ListNode* head) { ListNode* prev = nullptr; ListNode* curr = head; while (curr) { ListNode* nxt = curr->next; curr->next = prev; prev = curr; curr = nxt; } return prev; }public: ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) { l1 = reverseList(l1); l2 = reverseList(l2); ListNode dummy(0); ListNode* curr = &dummy; int carry = 0; while (l1 || l2 || carry) { int sum = carry + (l1 ? l1->val : 0) + (l2 ? l2->val : 0); carry = sum / 10; curr->next = new ListNode(sum % 10); curr = curr->next; if (l1) l1 = l1->next; if (l2) l2 = l2->next; } return reverseList(dummy.next); }}; int main() { ListNode* l1 = new ListNode(7); l1->next = new ListNode(2); l1->next->next = new ListNode(4); l1->next->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)— Reversing both lists takes O(N + M), adding takes O(max(N, M)), and final reversal takes O(max(N, M)). - Space complexity:
O(1) auxiliary space— Mutates pointers in place without auxiliary data structures.
Why Brute Force Doesn't Scale:
Converting linked list numbers directly into standard 64-bit integer types fails beyond 18 digits.
For two 500-digit numbers, dual-stack simulation requires less than 50KB RAM and finishes in under 1ms.