Merge Two Sorted Linked Lists in Java

🔥 Day 99 of #100DaysOfCode Today’s problem: LeetCode – Merge Two Sorted Lists 🔗📊 📌 Problem Summary You are given two sorted linked lists. 👉 Merge them into one sorted linked list and return the head. Example: list1 = [1,2,4] list2 = [1,3,4] Output → [1,1,2,3,4,4] 🧠 Approach: Recursion We compare nodes from both lists and recursively build the merged list. ⚙️ Logic 1️⃣ Base cases: If list1 == null → return list2 If list2 == null → return list1 2️⃣ Compare current nodes: If list1.val <= list2.val → attach list1 and recurse Else → attach list2 and recurse 💻 Code Insight if(list1.val <= list2.val){ list1.next = mergeTwoLists(list1.next, list2); return list1; }else{ list2.next = mergeTwoLists(list1, list2.next); return list2; } 💡 Why Recursion Works? Each step: Picks the smaller node Reduces the problem size Eventually reaches base case → builds sorted list naturally. ⏱ Time Complexity: O(n + m) 💾 Space Complexity: O(n + m) (recursion stack) 🚀 Performance Runtime: 0 ms Beats 100% submissions 🔥 Memory: 44.23 MB 🧠 Key Learning This problem is fundamental for: Linked list manipulation Divide & conquer Merge sort logic 🚨 Almost There! Just 1 day left to complete the #100DaysOfCode challenge 🎯🔥 From basics → advanced patterns → consistency. On to the final Day 100 🚀 #100DaysOfCode #LeetCode #LinkedList #Recursion #Java #DSA #InterviewPrep

  • No alternative text description for this image

To view or add a comment, sign in

Explore content categories