Problem
Given two sorted linked lists, write an algorithm to print the common elements of these lists. The solution should be based on the logic of merge sort. Since the elements in the lists are sorted, we can use a two-pointer technique to efficiently find and print the common elements.
Examples:
Example 1:
| |
Example 2:
| |
Solution
Method 1 - Using Merge sort logic
Initialize Two Pointers:
- Use two pointers to traverse both lists, starting from the heads of
list1andlist2.
- Use two pointers to traverse both lists, starting from the heads of
Traverse and Compare:
- Run a loop until you reach the end of either list.
- Compare the values of the nodes pointed to by the two pointers.
- If the values are equal, it means the current element is common in both lists. Print it or add it to the common list.
- If the value in
list1is less than the value inlist2, move the pointer inlist1forward. - If the value in
list1is greater than the value inlist2, move the pointer inlist2forward. - If the values are equal, move both pointers forward.
Return the Result:
- The common elements are printed or returned as required.
Code
| |
| |
Complexity
- ⏰ Time complexity:
O(m + n), wheremandnare the lengths oflist1andlist2respectively. We traverse both lists once. - 🧺 Space complexity:
O(l), whereLis the number of common elements.