Merge two sorted linked lists without rebuilding everything from scratch.
#leetcode #algorithms #datastructures
Merge two sorted linked lists without rebuilding everything from scratch.
LeetCode 21 looks simple, but the key is comparing the current nodes of both lists and always attaching the smaller one to the merged list.
So we keep track of three pointers:
prev → the end of the merged list
list1 → the current node in the first list
list2 → the current node in the second list
Then repeat:
compare → attach → advance → advance
Result: O(n + m) time and O(1) auxiliary space.
#LeetCode #Algorithms #DataStructures #PythonProgramming
____
Music by Vincent Rubinetti
Download the music on Bandcamp:
Stream the music on Spotify:
Comments
Comments from the original post on Instagram
No comments yet
