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

๐Ÿ› ๏ธ 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

๐Ÿ“š Reference Solution

โ–ผ
โŒ˜K Search โŒ˜โ†ฉ Run โŒ˜S Submit