MediumLinked ListMathRecursion

Add Two Numbers

LeetCode
1 approach, code in all languages

You are given two non-empty linked lists that each represent a non-negative integer. The digits are stored in reverse order, so the head of the list holds the least significant digit, and every node contains exactly one digit.

Add the two numbers together and return the result as a linked list, using the same reverse-order digit layout. You may assume that neither number has any leading zeros, except for the number zero itself.

Example 1

Input: l1 = [2,4,3], l2 = [5,6,4]

Output: [7,0,8]

The lists encode 342 and 465. Their sum is 807, which written back in reverse-digit order is 7 -> 0 -> 8.

Example 2

Input: l1 = [9,9,9], l2 = [1]

Output: [0,0,0,1]

This is 999 + 1 = 1000. The carry ripples through every digit and produces a new most significant node, giving 0 -> 0 -> 0 -> 1.

Constraints

  • The number of nodes in each list is in the range [1, 100].
  • 0 <= Node.val <= 9
  • Each list represents a number without leading zeros (except the value 0).
  • The combined result can exceed 10^30, so process it digit by digit rather than as a native integer.
You've got the patterns

Patterns get you through the screen. Shipping gets you hired.

FDE Coach is a cohort-based program in frontend, backend, AWS, and AI where you build real products and get referred to 200+ hiring partners. The free live workshop is the fastest way to see how we teach.

750+ engineers trained · frontend, backend, AWS & AI

August 15 · 0d left
Enroll Now