MEDIUM NC#40 Linked List
2. Add Two Numbers
๐ Problem
You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order, and each of their nodes contains a single digit. Add the two numbers and return the sum as a linked list. You may assume the two numbers do not contain any leading zero, except the number 0 itself.
๐ง Visual Learning Aid
1 Model the input into the right structure
2 Choose the core technique and invariant
3 Execute step-by-step with a sample
4 Validate complexity and edge cases
JS/TS Refreshers
- โขArray methods (`push`, `pop`, `shift`, `slice`)
- โขObject/Map/Set usage patterns
- โขFunction parameter and return typing
Logical Thinking Concepts
- โขDefine invariants before coding
- โขCheck edge cases first (`[]`, single element, duplicates)
- โขEstimate time/space before implementation
๐ก Approach
- โ Use dummy head to simplify list construction
- โ Track carry while iterating through both lists
- โ Handle different length lists by treating missing nodes as 0
- โ Time: O(max(m, n)), Space: O(max(m, n)) where m, n are list lengths
๐งญ Prerequisites
๐ ๏ธ Hints & Pitfalls
Hints
- โขUse dummy head to simplify list construction
- โขTrack carry while iterating through both lists
- โขHandle different length lists by treating missing nodes as 0
Common Pitfalls
- โขTime: O(max(m, n)), Space: O(max(m, n)) where m, n are list lengths
๐งช Test Cases
Hidden tests on submit: 1
Test Case 1
Not run Input:
addTwoNumbers(arrayToList([2,4,3]), arrayToList([5,6,4])); Expected:
{"val":7,"next":{"val":0,"next":{"val":8,"next":null}}} Test Case 2
Not run Input:
addTwoNumbers(arrayToList([0]), arrayToList([0])); Expected:
{"val":0,"next":null} Test Case 3
Not run Input:
addTwoNumbers(arrayToList([9,9,9,9,9,9,9]), arrayToList([9,9,9,9])); Expected:
{"val":8,"next":{"val":9,"next":{"val":9,"next":{"val":9,"next":{"val":0,"next":{"val":0,"next":{"val":0,"next":{"val":1,"next":null}}}}}}}} ๐ Code Editor
๐ค Output