Algorithm-Day27-Merge-Two-Sorted-Lists-lc-21
π§© Problem Description
You are given the heads of two sorted linked lists list1
and list2
.
Merge the two lists into one sorted list and return the new head.
Example:
1 | Input: list1 = [1,2,4], list2 = [1,3,4] |
π‘ Intuition
This is similar to the merge step in merge sort.
At each step, compare the two current nodes:
- Choose the smaller one
- Move its pointer forward
π’ Java Code (Iterative)
1 | class Solution { |
π Java Code (Recursive)
1 | class Solution { |
β± Time and Space Complexity
- Time Complexity: O(n + m)
- Space Complexity:
- Iterative: O(1)
- Recursive: O(n + m) due to call stack
βοΈ Summary
- A classic linked list problem β appears in merge sort, linked list manipulation, and more.
- Be comfortable with both iterative and recursive approaches.
- Dummy node makes code simpler and cleaner.
One of the most fundamental problems to master for linked list and recursion.