← Microsoft bank

Microsoft · Question 23 · Linked Lists

Intersection of Two Linked Lists

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

Problem

Find the node where two singly linked lists intersect or null if they do not intersect.

Approach

Both pointers traverse both lists, meeting at the intersection.

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

How it works

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

Sample input / output

Input:
2 3 3
4 1
5 6 1
8 4 5
Output:
8

Constraints

1 <= nodes <= 3 * 10^4; 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 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 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 ListNodetailOf(ListNode h)while (h.next != null)h = h.nextRETURN hDEFINE static voidmain(String[] args)java.util.Scanner sc = newjava.util.Scanner(System.in)DEFINE na = sc.nextInt();int nb = sc.nextInt(); intns = sc.nextInt()DEFINE [] av = new int[na];for (int i = 0; i < na;i++) av[i] = sc.nextInt()DEFINE [] bv = new int[nb];for (int i = 0; i < nb;i++) bv[i] = sc.nextInt()DEFINE [] sv = new int[ns];for (int i = 0; i < ns;i++) sv[i] = sc.nextInt()ListNode shared =buildList(sv)ListNode a = buildList(av);tailOf(a).next = sharedListNode b = buildList(bv);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/36

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