Live Batches
Masterclasses
Menu
Free Courses
Account
Login / Sign Up

Intersection of Two Linked Lists

Easy Acceptance 35.30% Points 20.00

Given two linked lists, head1 and head2, identify the intersection of the two lists. Both linked lists have unique node values with no duplicates.

Note: The nodes in the resulting list should maintain the same order as they appear in the input list head1. If there are no common elements between the two lists, return null.

Examples
Example 1

Example 1

Input: LinkedList1: 9 -> 7 -> 5 -> 3 -> 1, LinkedList2: 7 -> 1 -> 4 -> 3

Output: 7 -> 3 -> 1

Explanation: Nodes 7, 3, and 1 are common in both lists, and their order is maintained as in LinkedList1.

Example 2

Example 2

Input: LinkedList1: 2 -> 4 -> 6 -> 8 -> 10 -> 12, LinkedList2: 1 -> 3 -> 5 -> 7 -> 9 -> 11

Output: null

Explanation: There are no common elements between the two lists, so the output is an empty list.

Hints
Hint 1
Expected Time Complexity: O(m+n)
Hint 2
Expected Space Complexity: O(m+n)
Constraints
  • 1 <= no. of nodes in head1, head2 <= 10^4
  • 1 <= node->data <= 10^5
Companies
Amazon Microsoft Visa Flipkart
Topics
Linked List
Solution.cs C#JavaPythonC++Javascript

Unlock the code editor

Sign in to write, run, and submit your solution against the full test suite.

  • Run code against sample & hidden test cases
  • Save submissions and track your streak
  • Compare with editorial & community solutions