← Deloitte bank

Deloitte · Question 46 · Linked Lists

Intersection of Two Linked Lists

Linked ListsJavacode⏱ O(m + n)💾 O(1)
Service-based

Problem

Find the node where two singly linked lists intersect.

Approach

Two-pointer switching trick; both become null without intersection.

Time O(m + n)Space O(1)

How it works

  1. 1Each pointer switches lists once.
  2. 2Equal total distance aligns them at the intersection.

Sample input / output

Input:
headA = [4, 1, 8, 4, 5], headB = [5, 6, 1, 8, 4, 5]
Output:
8

Constraints

O(1) extra memory.

Solution — read it, then walk it

Time O(m + n)Space O(1)Loops 4Branches 1Returns 4source · 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 ListNodegetIntersectionNode(ListNodeheadA, ListNode headB)if (headA == null ||headB == null) returnnullListNode a = headA, b =headBwhile (a != b)a = (a == null) ? headB :a.nextb = (b == null) ? headA :b.nextRETURN aDEFINE ListNodetailOf(ListNode h)while (h.next != null)h = h.nextRETURN hDEFINE static voidmain(String[] args)ListNode shared =buildList(new int[]{8, 4,5})ListNode a = buildList(newint[]{4, 1})tailOf(a).next = sharedListNode b = buildList(newint[]{5, 6, 1})tailOf(b).next = sharedListNode node =getIntersectionNode(a, b)System.out.println(node ==null ? "null" : node.val)END
  • start / end
  • statement
  • condition
  • loop
  • returns
  • definition
1/33

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