← Google bank

Google · Question 29 · Linked Lists

Add Two Numbers

Linked ListsPythoncode⏱ O(max(n,m))💾 O(max(n,m))
Product-based

Problem

Add two numbers represented by linked lists where each node contains a digit in reverse order.

Approach

Iterate nodes, sum digits with carry, create new list.

Time O(max(n,m))Space O(max(n,m))

How it works

  1. 1Sum digits and carry while iterating both lists.
  2. 2Use divmod to split each sum into digit and carry.
  3. 3Create a new node for each result digit.
  4. 4Continue until both lists and the carry are processed.

Sample input / output

Input:
3
2 4 3
3
5 6 4
Output:
[7, 0, 8]

Constraints

1 <= nodes <= 100; 0 <= Node.val <= 9; digits stored in reverse order.

Solution — read it, then walk it

Time O(max(n,m))Space O(max(n,m))Loops 3Branches 1Returns 3source · Python
Scroll sideways for wide charts — the view follows the active step.
↻ repeat↻ repeat↻ repeatyesnoSTARTl1, l2dummy = tail = ListNode()carry = 0while l1 or l2 orcarryval1 = l1.val if l1 else 0val2 = l2.val if l2 else 0carry, out = divmod(val1 +val2 + carry, 10)tail.next = ListNode(out)tail = tail.nextl1 = l1.next if l1 elseNonel2 = l2.next if l2 elseNoneRETURN dummy.nextCLASS ListNodeDEFINE __init__(self,val=0, next=None)self.val = valself.next = nextDEFINE build_list(values)dummy = tail = ListNode()for v in valuestail.next = ListNode(v)tail = tail.nextRETURN dummy.nextDEFINE to_list(head)out = []while headout.append(head.val)head = head.nextRETURN outDEFINE main()import sysdata =sys.stdin.read().split()it = iter(data)n = int(next(it)); a =[int(next(it)) for _ inrange(n)]m = int(next(it)); b =[int(next(it)) for _ inrange(m)]print(to_list(addTwoNumbers(build_list(a),build_list(b))))if __name__ =="__main__"main()END
  • start / end
  • statement
  • condition
  • loop
  • returns
  • definition
1/38

StartSTART

Interactive control-flow diagram and step-by-step code walkthrough.

Recommended resourcesAffiliate links · may earn us a commission

Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Cloud hosting for side projectsShip the portfolio project that gets you hired — free credits for new accounts.Claim credits