This problem follows the Two Pointer Merge pattern, commonly found in the Linked List category. Recognizing this pattern is key to solving it efficiently in an interview setting.
Compare heads. Append smaller to result. Advance that pointer.
The dummy node eliminates the need for special-casing the head — you always have a 'previous' node to attach to.
dummy = ListNode(0)
curr = dummy
while l1 and l2:
if l1.val <= l2.val:
curr.next = l1
l1 = l1.next
else:
curr.next = l2
l2 = l2.next
curr = curr.next
curr.next = l1 or l2
return dummy.nextPractice Merge Two Sorted Lists and similar Linked List problems with flashcards. Build pattern recognition through active recall.
Practice this problem