← Deloitte bank

Deloitte · Question 43 · Linked Lists

Add Two Numbers

Linked ListsJavacode⏱ O(max(m,n))💾 O(max(m,n)
Service-based

Problem

Sum two numbers represented as reverse-order linked lists.

Approach

Walk both lists together, adding the paired digits plus any carry and building a fresh result list.

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

How it works

  1. 1Add paired digits plus carry each round.
  2. 2Emit digit, carry the tens onward.

Sample input / output

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

Constraints

Digits in reverse order; 1 <= nodes <= 100.

Solution — read it, then walk it

Time O(max(m,n))Space O(max(m,n)Loops 3Branches 2Returns 3source · Java
Scroll sideways for wide charts — the view follows the active step.
↻ repeatSTARTimport java.util.*DEFINE class MainDEFINE class ListNodeDEFINE valListNode nextListNode(int v) { val = v;}DEFINE ListNodebuildList(int[] values)ListNode dummy = newListNode(0), tail = dummyfor (int v : values) {tail.next = newListNode(v); tail …RETURN dummy.nextDEFINE StringtoList(ListNode head)StringBuilder sb = newStringBuilder("[")while (head != null) {sb.append(head.val);head = head.next; i…RETURNsb.append("]").toString()DEFINE static ListNodeaddTwoNumbers(ListNode l1,ListNode l2)ListNode dummy = newListNode(0), p = dummyDEFINE carry = 0while (l1 != null ||l2 != null || carry !=0)DEFINE s = carry + (l1 !=null ? l1.val : 0) + (l2 !=null ? l2.val : 0)p.next = new ListNode(s %10)carry = s / 10p = p.nextif (l1 != null) l1 =l1.nextif (l2 != null) l2 =l2.nextRETURN dummy.nextDEFINE static voidmain(String[] args)System.out.println(toList(addTwoNumbers(buildList(newint[]{2, 4, 3}),buildList(new int[]{5, 6…END
  • start / end
  • statement
  • condition
  • loop
  • returns
  • definition
1/28

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