Merge Two Sorted Lists - JS Solution

JS
Editorial

Solution explanation

Solution explanation

Approach

  • We use a dummy node (gray) to simplify edge cases β€” it serves as a dummy head for the merged list, whose next pointer refers to the current real head of the merged list. Initially, its next is null, since the merged list starts empty.
  • Maintain a pointer mergedListTail that always refers to the current last node in the merged list. Initially, it points to the dummy node, because at the start, the merged list contains no real nodes β€” only the dummy head.
  • While both lists have nodes:
    • Compare the heads of the two lists (list1 vs list2).
    • Attach the smaller head after mergedListTail.
    • Advance the head pointer of that list and move mergedListTail forward to the newly attached node.
  • When one list becomes empty, append all remaining nodes from the other list directly to the merged list. Simply setting mergedListTail.next to the remaining list’s head is enough to connect the rest.
  • The merged result starts from dummy.next, since the dummy node itself is only a helper and its next pointer always references the real head of the merged list.

Time Complexity

O(n + m) β€” where n and m are the lengths of the two input linked lists. Each node is visited at most once during the merge process.

Space Complexity

O(1) β€” we merge the lists by reusing existing nodes and links. Only a few pointer variables are maintained, and the output list doesn’t count as extra space since it’s formed by simply relinking the original nodes, without creating any new nodes or links.

Visucodize editorial solution titled JS Solution for LeetCode's Merge Two Sorted Lists coding problem. Includes code and may include explanation. You can animate the code step by step using the provided input by clicking the run button, or fork it locally to update the code and input for custom visualization. View the original problem at https://leetcode.com/problems/merge-two-sorted-lists.