l1 = [2,4,3]
l2 = [5,6,4][7,0,8]Two nonempty linked lists represent nonnegative integers. Each node holds one digit, with the ones digit first. Return a new linked list representing their sum in the same reverse-digit order.
l1 = [2,4,3]
l2 = [5,6,4][7,0,8]342 + 465 = 807. The nodes store digits in reverse order.
l1 = [9,9]
l2 = [1][0,0,1]99 + 1 = 100. The final carry needs one more node.
Each input has 1 to 100 nodes, with digits from 0 to 9. The last digit cannot be zero unless the entire number is zero. Inputs stay unchanged.
LeetCode 2 ↗l1 = [2,4,3] l2 = [5,6,4] output: [7,0,8]
For input lengths m and n, copying and adding digits takes O(m + n) time.
The copied arrays use O(m + n) auxiliary space. The returned list separately uses O(max(m, n)) space, with at most one extra carry node.
l1 = [2,4,3] l2 = [5,6,4] output: [7,0,8]
Both approaches are linear-time. Direct addition avoids copying input digits, reducing auxiliary space from O(m + n) to O(1). The output list still requires space.
Each input node is visited once. For lengths m and n, time complexity is O(m + n).
O(1) auxiliary space for references, digits, and carry. Excluding auxiliary space, the returned list uses O(max(m, n)) space.