Merge Two Sorted Linked Lists in Python

Day 6 of #200DaysOfCode! 🚀 Sticking with the Linked List theme, today I tackled one of the most essential problems in the data structure's repertoire: "Merge Two Sorted Lists" (LeetCode 21). If yesterday was about math on lists, today was about structure. The Challenge: Given two sorted linked lists, merge them into one single sorted list. Think of it like shuffling two decks of cards that are already sorted, or zipping a zipper. The Logic (The Zipper Technique): I used an iterative approach with Two Pointers (i for list1, j for list2) and a "Dummy Node" to build the result. Comparison: I compare the values at the head of both lists (i.val vs j.val). Selection: I pick the smaller value, add it to my new list, and move that specific pointer forward. The Loop: I keep doing this until one of the lists runs dry. The Cleanup: Once one list is empty, I simply append the remaining elements of the other list to the end (since they are already sorted!). The Result: Another 0 ms runtime, beating 100.00% of Python submissions! ⚡ It is a simple algorithm, but it is the exact same logic used in the "Merge" step of Merge Sort, making it a powerful pattern to master. Day 6 down. The streak is alive and well! 🔥 Do you prefer solving this Iteratively (like I did) or Recursively? The recursive solution is elegant but scary for large lists! 👇 #200DaysOfCode #Python #LeetCode #LinkedList #Algorithms #MergeSort #TwoPointers #ProblemSolving #CodingChallenge #DeveloperJourney

  • text

To view or add a comment, sign in

Explore content categories