← Uber bank

Uber · Question 17 · Linked Lists

Add two numbers represented by linked lists

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

Problem

Add two numbers stored in linked lists.

Approach

Add digits one by one, managing carry.

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

How it works

  1. 1Add paired digits plus carry each round.
  2. 2Store total % 10 and carry total // 10.
  3. 3Continue while either list or carry remains.

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 in reverse order; no leading zeros.

Solution — read it, then walk it

Time O(max(n,m))Space O(max(n,m))Loops 3Branches 3Returns 3source · Python
Scroll sideways for wide charts — the view follows the active step.
yesnoyes↻ repeat↻ repeat↻ repeat↻ repeatyesnoSTARTl1, l2dummy = ListNode(0)current = dummycarry = 0while l1 or l2 orcarryval1 = l1.val if l1 else 0val2 = l2.val if l2 else 0total = val1 + val2 + carrycarry = total // 10current.next =ListNode(total % 10)current = current.nextif l1l1 = l1.nextif l2l2 = l2.nextRETURN 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/42

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