Intersection of two Sorted Linked List

Pattern: Merging and sorting

medium

Walk both sorted lists together. Equal fronts are common, so copy the value and move both. Otherwise the smaller front can never match anything later, so move only that list.

No verified practice link yet. The guide below states the problem in full, so you can still solve it here.

The problem

Given two linked lists sorted in increasing order, return a new sorted list of the values they have in common. A value that appears twice in both lists appears twice in the answer; in general each copy in one list is matched with at most one copy in the other. The input lists stay unchanged. For example, 1 → 2 → 3 → 4 → 6 and 2 → 4 → 6 → 8 give 2 → 4 → 6.

This problem is from Love Babbar's 450 sheet, and this guide has no verified link for it yet. The function name findIntersection and the rule for repeated values are this guide's own.

Think first

  • When the two fronts are equal, what do you do?
  • When they differ, which front can be thrown away for good?
  • Should the answer reuse input nodes or make new ones?

Hints

    Brute force, and why it fails

    For each node of one list, search the other: O(m × n). A hash map of counts is O(m + n) but ignores the sorted order. The two-front walk is O(m + n) with O(1) extra memory besides the answer.

    The key insight

    Sorted order lets you discard the smaller front without looking further, exactly as in merging. One walk finds every common value.

    Dry run

    1 2 3 4 60 
    2 4 6 81 
    out

    head1 = 1 → 2 → 3 → 4 → 6 and head2 = 2 → 4 → 6 → 8.

    Step 1 of 4

    The plan

    dummy, tail = new node
    while head1 and head2:
        if head1.val == head2.val:
            tail.next = new node(head1.val); tail = tail.next
            head1 = head1.next; head2 = head2.next
        else if head1.val < head2.val: head1 = head1.next
        else: head2 = head2.next
    return dummy.next
    

    Complexity

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

    Each step moves at least one list. The new list is the output.

    Edge cases

    • Nothing in common: empty.
    • Repeated values, as in 1 → 1 → 2 and 1 → 1 → 1: 1 → 1.
    • One list empty: empty.
    I've built my logic, show the code

    Java

    class Solution {
        public ListNode findIntersection(ListNode head1, ListNode head2) {
            ListNode dummy = new ListNode(0), tail = dummy;
            while (head1 != null && head2 != null) {
                if (head1.val == head2.val) {                // common: copy it and move both
                    tail.next = new ListNode(head1.val);
                    tail = tail.next;
                    head1 = head1.next;
                    head2 = head2.next;
                } else if (head1.val < head2.val) {
                    head1 = head1.next;                      // the smaller front cannot match anything later
                } else {
                    head2 = head2.next;
                }
            }
            return dummy.next;
        }
    }

    C++

    class Solution {
    public:
        ListNode* findIntersection(ListNode* head1, ListNode* head2) {
            ListNode dummy(0);
            ListNode* tail = &dummy;
            while (head1 != NULL && head2 != NULL) {
                if (head1->val == head2->val) {              // common: copy it and move both
                    tail->next = new ListNode(head1->val);
                    tail = tail->next;
                    head1 = head1->next;
                    head2 = head2->next;
                } else if (head1->val < head2->val) {
                    head1 = head1->next;                     // the smaller front cannot match anything later
                } else {
                    head2 = head2->next;
                }
            }
            return dummy.next;
        }
    };

    Python

    from lib import ListNode
    
    class Solution:
        def findIntersection(self, head1: ListNode, head2: ListNode) -> ListNode:
            dummy = tail = ListNode(0)
            while head1 is not None and head2 is not None:
                if head1.val == head2.val:          # common: copy it and move both
                    tail.next = ListNode(head1.val)
                    tail = tail.next
                    head1, head2 = head1.next, head2.next
                elif head1.val < head2.val:
                    head1 = head1.next              # the smaller front cannot match anything later
                else:
                    head2 = head2.next
            return dummy.next

    Common mistakes

    • Moving the bigger front, which skips matches.
    • Moving only one list after a match, which counts the same value again.
    • Relinking input nodes into the answer, which breaks the input lists.

    Similar problems