Merge and remove problems
35 min · Intermediate
Need help? Ask a tutor on WhatsApp (opens in a new tab)Combining a dummy head node with two pointers turns four classic linked-list problems into clean 10-line methods. These four patterns cover sorted merges, n-th node removal from the end, deduplication, and list intersection.
Merge two sorted lists and remove the nth node from the end
In Merge Two Sorted Lists, splice l1 and l2 into one list in O(1) space. Create Node dummy = new Node(0, null) and Node tail = dummy. While l1 != null && l2 != null, attach the smaller head to tail.next and advance.
- Create
Node dummy = new Node(0, head)and start bothslow = dummyandfast = dummy. - Advance
fastbyn + 1steps so there is a gap ofnnodes betweenslowandfast. - Advance both
slow = slow.nextandfast = fast.nexttogether untilfast == null. - Now
slowstands on the predecessor of the target node; setslow.next = slow.next.next;andreturn dummy.next;.
Example 1 · Brute force: count the length first, then delete (two passes, O(n) time, O(1) extra space)
public class RemoveNthTwoPassDemo { static class Node { int val; Node next; Node(int val, Node next) { this.val = val; this.next = next; } }
static Node removeNthFromEnd(Node head, int n) { int length = 0; for (Node curr = head; curr != null; curr = curr.next) length++;
Node dummy = new Node(0, head); Node prev = dummy; for (int i = 0; i < length - n; i++) prev = prev.next; prev.next = prev.next.next; return dummy.next; }
static String show(Node head) { StringBuilder sb = new StringBuilder(); for (Node curr = head; curr != null; curr = curr.next) sb.append(curr.val).append(" -> "); return sb.append("null").toString(); }
public static void main(String[] args) { Node head = new Node(1, new Node(2, new Node(3, new Node(4, new Node(5, null))))); System.out.println(show(removeNthFromEnd(head, 2))); System.out.println(show(removeNthFromEnd(new Node(9, null), 1))); }}1 -> 2 -> 3 -> 5 -> null null
What this code does
- The first loop counts the list, so the node to delete is at position
length - nfrom the front. The second loop stops on its predecessor. - The
dummynode makes deleting the head work the same way as deleting any other node. - Both loops are O(n) and use no extra memory. The gap-pointer version in the next example reads the list only once.
Example 2 · Optimal: merge two sorted lists and remove the nth node in one pass (O(n) time, O(1) space)
public class MergeAndRemoveNthDemo { static class Node { int val; Node next; Node(int val, Node next) { this.val = val; this.next = next; } }
public static Node mergeTwoLists(Node l1, Node l2) { Node dummy = new Node(0, null); Node tail = dummy; while (l1 != null && l2 != null) { if (l1.val <= l2.val) { tail.next = l1; l1 = l1.next; } else { tail.next = l2; l2 = l2.next; } tail = tail.next; } tail.next = (l1 != null) ? l1 : l2; return dummy.next; }
public static Node removeNthFromEnd(Node head, int n) { Node dummy = new Node(0, head); Node slow = dummy, fast = dummy; for (int i = 0; i <= n; i++) { fast = fast.next; } while (fast != null) { slow = slow.next; fast = fast.next; } slow.next = slow.next.next; return dummy.next; }
static String format(Node head) { StringBuilder sb = new StringBuilder(); for (Node c = head; c != null; c = c.next) sb.append(c.val).append(" -> "); return sb.append("null").toString(); }
public static void main(String[] args) { Node a = new Node(1, new Node(3, new Node(5, null))); Node b = new Node(2, new Node(4, new Node(6, null))); Node merged = mergeTwoLists(a, b); System.out.println("Merged: " + format(merged));
merged = removeNthFromEnd(merged, 2); // Remove 2nd from end (5) System.out.println("After removing 2nd from end: " + format(merged)); merged = removeNthFromEnd(merged, 5); // Remove 5th from end (head=1) System.out.println("After removing 5th from end: " + format(merged)); }}Merged: 1 -> 2 -> 3 -> 4 -> 5 -> 6 -> null After removing 2nd from end: 1 -> 2 -> 3 -> 4 -> 6 -> null After removing 5th from end: 2 -> 3 -> 4 -> 6 -> null
What this code does
mergeTwoListsrewires existing nodes usingdummyandtailin O(n + m) time and O(1) space.removeNthFromEndadvancesfastbyn + 1steps fromdummysoslowstops at the predecessor of the target node.
When one list runs out, you do not need a loop for the other list. Just write tail.next = (l1 != null) ? l1 : l2; to attach the remaining chain in O(1)! In Remove Nth Node From End, stop at the node before the n-th from the end. Keep a fixed gap of n steps between fast and slow.
dummy here? If n equals the list length, the node to delete is head. Starting slow at dummy lets slow.next = slow.next.next delete head cleanly.Remove duplicates from a sorted list (I and II)
When a linked list is already sorted, all duplicate values sit next to each other.
Example 3 · Remove Duplicates from Sorted List I (Keep 1) vs II (Keep 0)
public class RemoveDuplicatesDemo { static class Node { int val; Node next; Node(int val, Node next) { this.val = val; this.next = next; } }
public static Node deleteDuplicatesKeepOne(Node head) { Node curr = head; while (curr != null && curr.next != null) { if (curr.val == curr.next.val) { curr.next = curr.next.next; } else { curr = curr.next; } } return head; }
public static Node deleteDuplicatesKeepZero(Node head) { Node dummy = new Node(0, head); Node prev = dummy; while (prev.next != null && prev.next.next != null) { if (prev.next.val == prev.next.next.val) { int dupVal = prev.next.val; while (prev.next != null && prev.next.val == dupVal) { prev.next = prev.next.next; } } else { prev = prev.next; } } return dummy.next; }
static String format(Node head) { StringBuilder sb = new StringBuilder(); for (Node c = head; c != null; c = c.next) sb.append(c.val).append(" -> "); return sb.append("null").toString(); }
public static void main(String[] args) { Node list1 = new Node(1, new Node(1, new Node(2, new Node(3, new Node(3, null))))); System.out.println("Keep 1 copy: " + format(deleteDuplicatesKeepOne(list1)));
Node list2 = new Node(1, new Node(1, new Node(2, new Node(3, new Node(3, new Node(4, null)))))); System.out.println("Keep 0 of dups: " + format(deleteDuplicatesKeepZero(list2))); }}Keep 1 copy: 1 -> 2 -> 3 -> null Keep 0 of dups: 2 -> 4 -> null
What this code does
- In
deleteDuplicatesKeepOne,1 -> 1 -> 2 -> 3 -> 3retains one copy of1and one copy of3. - In
deleteDuplicatesKeepZero, any number that appears two or more times (1and3) is stripped completely, leaving2 -> 4.
In Remove Duplicates I (1 -> 1 -> 2 -> 3 -> 3 to 1 -> 2 -> 3), you keep one copy of each value. Walk curr = head: when curr.next != null && curr.val == curr.next.val, set curr.next = curr.next.next;; else advance curr = curr.next;. In Remove Duplicates II (1 -> 1 -> 2 -> 3 -> 3 -> 4 to 2 -> 4), you delete all copies of any duplicated value. Use Node dummy = new Node(0, head) and Node prev = dummy. When prev.next and prev.next.next share dupVal, advance prev.next past every node with dupVal.
Quick comparison:
- Keep 1 copy: no dummy needed; compare
curr.val == curr.next.val. - Remove all copies of duplicates: use a dummy head and skip the full
dupValrun.
Intersection of two linked lists
In Intersection of Two Linked Lists, headA and headB may share a suffix of length c. How do we find the first shared node in O(a + b) time and O(1) space?
Example 4 · Brute force: compare every node of A with every node of B (O(m * n) time, O(1) extra space)
public class IntersectionBruteDemo { static class Node { int val; Node next; Node(int val, Node next) { this.val = val; this.next = next; } }
static Node intersect(Node headA, Node headB) { for (Node a = headA; a != null; a = a.next) { for (Node b = headB; b != null; b = b.next) { if (a == b) return a; } } return null; }
public static void main(String[] args) { Node shared = new Node(8, new Node(10, null)); Node headA = new Node(4, new Node(1, shared)); Node headB = new Node(5, new Node(6, new Node(1, shared))); Node meet = intersect(headA, headB); System.out.println("Intersection node val: " + (meet != null ? meet.val : "null")); }}Intersection node val: 8
What this code does
a == bcompares node references, so the two separateNode(1)objects are not mistaken for each other.- For each of the m nodes of A the inner loop may walk all n nodes of B: O(m * n) time and no extra memory.
- Remembering one list in a set removes the inner loop, as shown next.
Example 5 · Better: store the nodes of A in a HashSet, then walk B (O(m + n) time, O(m) extra space)
import java.util.HashSet;import java.util.Set;
public class IntersectionSetDemo { static class Node { int val; Node next; Node(int val, Node next) { this.val = val; this.next = next; } }
static Node intersect(Node headA, Node headB) { Set<Node> inA = new HashSet<>(); for (Node a = headA; a != null; a = a.next) inA.add(a); for (Node b = headB; b != null; b = b.next) { if (inA.contains(b)) return b; } return null; }
public static void main(String[] args) { Node shared = new Node(8, new Node(10, null)); Node headA = new Node(4, new Node(1, shared)); Node headB = new Node(5, new Node(6, new Node(1, shared))); Node meet = intersect(headA, headB); System.out.println("Intersection node val: " + (meet != null ? meet.val : "null")); }}Intersection node val: 8
What this code does
inA.contains(b)is an O(1) average lookup, so each node of B costs one step instead of a scan of A.- Total time drops to O(m + n), but the set stores all m nodes of A: O(m) extra space.
- The two-pointer version in the next example keeps O(m + n) time and needs no set at all.
Example 6 · Optimal: swap heads at the end of each list (O(m + n) time, O(1) space)
public class IntersectionOfListsDemo { static class Node { int val; Node next; Node(int val, Node next) { this.val = val; this.next = next; } }
public static Node getIntersectionNode(Node headA, Node headB) { Node pA = headA; Node pB = headB; while (pA != pB) { pA = (pA == null) ? headB : pA.next; pB = (pB == null) ? headA : pB.next; } return pA; }
public static void main(String[] args) { Node shared = new Node(8, new Node(10, null)); Node headA = new Node(4, new Node(1, shared)); // length 4: 4->1->8->10 Node headB = new Node(5, new Node(6, new Node(1, shared))); // length 5: 5->6->1->8->10
Node meet = getIntersectionNode(headA, headB); System.out.println("Intersection node val: " + (meet != null ? meet.val : "null"));
Node disjoint = new Node(99, null); System.out.println("Disjoint intersection: " + getIntersectionNode(headA, disjoint)); }}Intersection node val: 8 Disjoint intersection: null
What this code does
- Both lists contain a
Node(1)beforeshared, but those are two separateNode(1)objects. The first shared object isshared(val = 8). - When
headAanddisjointdo not intersect,pAandpBboth hitnullafter 5 steps.
Start pA = headA and pB = headB. Advance each by 1 step, redirecting pA to headB at null and pB to headA at null. Before meeting, pA walks a + c + b steps and pB walks b + c + a. Both travel the exact same distance and meet at the first shared node (or at null if disjoint).
Remember:
- Intersection means reference equality (
pA == pB), not value equality (pA.val == pB.val). - If the lists do not intersect, both pointers hit
nullat step a + b and returnnull.
Next step
Check your understanding
10 quick questions