EasyNo. 0160

Intersection of Two Linked Lists — LeetCode 160 Python Solution

Topics
Hash Table, Linked List, Two Pointers
Reading time
3 min

The problem

Given the heads of two singly linked-lists headA and headB, return the node at which the two lists intersect. If the two linked lists have no intersection at all, return null.

Example

Input
intersectVal = 8, listA = [4,1,8,4,5], listB = [5,6,1,8,4,5], skipA = 2, skipB = 3
Output
Intersected at '8'
Explanation
The intersected node's value is 8 (note that this must not be 0 if the two lists intersect).

Python solution

PythonSolution
# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None


class Solution:
    def getIntersectionNode(self, headA: ListNode, headB: ListNode) -> ListNode:
        a, b = headA, headB
        while a != b:
            a = a.next if a else headB
            b = b.next if b else headA
        return a

Complexity

Time
O(m + n)where m and n are the lengths of the linked lists headA and headB, respectively
Space · auxiliary
O(1)

Pattern: Linked List

Rewire pointers in place, with a dummy head and a saved next to keep it safe. LeetCode 160. Intersection of Two Linked Lists is filed here because LeetCode tags it Linked List, which is the vocabulary this hub collects.

The linked list guide has the Python template for the pattern and the 75 LeetCode problems that use it.

Related problems

Related problems
No.ProblemDifficulty
0141Linked List CycleEasy
0142Linked List Cycle IIMedium
0138Copy List with Random PointerMedium
0146LRU CacheMedium
0202Happy NumberEasy
0349Intersection of Two ArraysEasy

Frequently asked questions

How hard is LeetCode 160. Intersection of Two Linked Lists?

LeetCode 160. Intersection of Two Linked Lists is rated Easy on LeetCode.

What is the time complexity of LeetCode 160. Intersection of Two Linked Lists?

The Python solution on this page runs in O(m + n), where m and n are the lengths of the linked lists \textit{headA} and \textit{headB}, respectively.

What is the space complexity of LeetCode 160. Intersection of Two Linked Lists?

The Python solution on this page uses O(1) auxiliary space.

What topics does LeetCode 160. Intersection of Two Linked Lists cover?

LeetCode 160. Intersection of Two Linked Lists is tagged Hash Table, Linked List and Two Pointers on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity, invisible to screen sharing.

Free to download. Check it runs on your machine, then pick a plan.