THN Interview Prep

2. Add Two Numbers

At a Glance

  • Topic: linked-list
  • Pattern: Linked-list arithmetic (digit-wise with carry)
  • Difficulty: Medium
  • Companies: Amazon, Google, Meta, Microsoft, Apple
  • Frequency: High
  • LeetCode: 2

Problem (one-liner)

Two non-empty linked lists store non-negative integers with most significant digit at the head (reverse digit order). Add the two numbers and return the sum as a linked list in the same digit order.

Recognition Cues

  • Digits as list nodes, least significant digit at head
  • Elementary school addition with carry
  • Lists may differ in length

Diagram

At-a-glance flow (replace with problem-specific Mermaid as you refine this note). camelCase node IDs; no spaces in IDs.

Loading diagram…

Approaches

  • Brute force — convert both lists to big integers, add, convert back — O(n) time but heavy and language-dependent.
  • Better — same.
  • OptimalO(max(m,n)) time / O(1) extra (besides output) — one pass, track carry, build result with dummy head.

Optimal Solution

Go

type ListNode struct {
	Val  int
	Next *ListNode
}

func addTwoNumbers(listA *ListNode, listB *ListNode) *ListNode {
	dummy := &ListNode{}
	tail := dummy
	carry := 0
	for listA != nil || listB != nil || carry > 0 {
		sum := carry
		if listA != nil {
			sum += listA.Val
			listA = listA.Next
		}
		if listB != nil {
			sum += listB.Val
			listB = listB.Next
		}
		carry = sum / 10
		tail.Next = &ListNode{Val: sum % 10}
		tail = tail.Next
	}
	return dummy.Next
}

JavaScript

class ListNode {
	constructor(val = 0, next = null) {
		this.val = val;
		this.next = next;
	}
}

function addTwoNumbers(listA, listB) {
	const dummy = new ListNode();
	let tail = dummy;
	let carry = 0;
	while (listA !== null || listB !== null || carry > 0) {
		let sum = carry;
		if (listA !== null) {
			sum += listA.val;
			listA = listA.next;
		}
		if (listB !== null) {
			sum += listB.val;
			listB = listB.next;
		}
		carry = Math.floor(sum / 10);
		tail.next = new ListNode(sum % 10);
		tail = tail.next;
	}
	return dummy.next;
}

Walkthrough

342 as 2 -> 4 -> 3, 465 as 5 -> 6 -> 4.

stepsum digitscarry outresult tail
12+5=707
24+6=1010
33+4+1=808

Output 807 as 7 -> 0 -> 8.

Edge Cases

  • Different lengths — missing side treated as 0.
  • Final overflow carry — loop until carry exhausted.
  • One list nil — still valid.

Pitfalls

  • Appending digits in wrong order — output built forward matches reverse-digit input.
  • Forgetting last carry after both lists end.

Similar Problems

Variants

  • MSB-first add — reverse lists or use stacks.
  • Multiply two numbers — more carry layers; chunking or FFT for huge sizes (out of scope).

Mind-Map Tags

#linked-list #carry #dummy-tail #school-addition

Last updated on

Spotted something unclear or wrong on this page?

On this page