EASY NC#36 Blind #42 Linked List

21. Merge Two Sorted Lists

๐Ÿ“– Problem

You are given the heads of two sorted linked lists list1 and list2. Merge the two lists into one sorted list. The list should be made by splicing together the nodes of the first two lists. Return the head of the merged linked list.

๐Ÿง  Visual Learning Aid

1 Model the input into the right structure
2 Choose the core technique and invariant
3 Execute step-by-step with a sample
4 Validate complexity and edge cases

JS/TS Refreshers

  • โ€ขArray methods (`push`, `pop`, `shift`, `slice`)
  • โ€ขObject/Map/Set usage patterns
  • โ€ขFunction parameter and return typing

Logical Thinking Concepts

  • โ€ขDefine invariants before coding
  • โ€ขCheck edge cases first (`[]`, single element, duplicates)
  • โ€ขEstimate time/space before implementation

๐Ÿ’ก Approach

  • โ†’ Use dummy head to simplify list construction
  • โ†’ Compare nodes from both lists and add smaller to result
  • โ†’ Append remaining nodes from the longer list
  • โ†’ Time: O(m + n), Space: O(1) (excluding result)

๐Ÿ› ๏ธ Hints & Pitfalls

Hints

  • โ€ขUse dummy head to simplify list construction
  • โ€ขCompare nodes from both lists and add smaller to result
  • โ€ขAppend remaining nodes from the longer list

Common Pitfalls

  • โ€ขTime: O(m + n), Space: O(1) (excluding result)

๐Ÿงช Test Cases

Hidden tests on submit: 1

Test Case 1
Not run
Input:
mergeTwoLists(arrayToList([1,2,4]), arrayToList([1,3,4]));
Expected:
{"val":1,"next":{"val":1,"next":{"val":2,"next":{"val":3,"next":{"val":4,"next":{"val":4,"next":null}}}}}}
Test Case 2
Not run
Input:
mergeTwoLists(arrayToList([]), arrayToList([]));
Expected:
null
Test Case 3
Not run
Input:
mergeTwoLists(arrayToList([]), arrayToList([0]));
Expected:
{"val":0,"next":null}

๐Ÿ“ Code Editor

๐Ÿ“š Reference Solution

โ–ผ
โŒ˜K Search โŒ˜โ†ฉ Run โŒ˜S Submit