Interleave Two Linked Lists - Problem

You are given the heads of two linked lists list1 and list2.

Interleave the nodes by alternating between the two lists: take the first node from list1, then the first node from list2, then the second node from list1, then the second node from list2, and so on.

If one list is longer than the other, append the remaining nodes at the end.

Return the head of the interleaved linked list.

Input & Output

Example 1 — Equal Length
$ Input: list1 = [1,3,5], list2 = [2,4,6]
Output: [1,2,3,4,5,6]
💡 Note: Alternate: 1(list1), 2(list2), 3(list1), 4(list2), 5(list1), 6(list2)
Example 2 — Unequal Length
$ Input: list1 = [1,2], list2 = [10,20,30,40]
Output: [1,10,2,20,30,40]
💡 Note: Alternate: 1(list1), 10(list2), 2(list1), 20(list2), then remaining from list2: 30, 40
Example 3 — One Empty
$ Input: list1 = [], list2 = [5,10]
Output: [5,10]
💡 Note: list1 is empty, so return list2 as-is

Constraints

  • The number of nodes in both lists is in the range [0, 50].
  • -100 ≤ Node.val ≤ 100

Visualization

Tap to expand
Interleave Two Linked Lists INPUT list1 1 3 5 list2 2 4 6 list1 = [1, 3, 5] list2 = [2, 4, 6] INTERLEAVE STEPS 1 Take from list1 Pick node 1 2 Take from list2 Pick node 2 3 Alternate 3, 4, 5, 6... Rewiring Flow: 1.next = 2, 2.next = 3 3.next = 4, 4.next = 5 5.next = 6, done! RESULT Interleaved List 1 2 3 4 5 6 null Output: [1, 2, 3, 4, 5, 6] OK - Interleaved! from list1 from list2 Key Insight: Save next pointers before rewiring. For each pair: list1.next = list2, list2.next = saved_list1_next. When one list runs out, the remaining nodes are already linked. No extra space needed. Time: O(m+n) | Space: O(1) - Only pointer manipulation, no extra space needed. TutorialsPoint - Interleave Two Linked Lists | In-Place Pointer Rewiring
Asked in
Amazon 45 Microsoft 32 Google 22
0 Views
High Frequency
~12 min Avg. Time
0 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen