Skip to the code
cf.
+10 XP

#244 Combine Two Sorted Feeds

easy

A social app loads posts from two sources, each a linked list of post timestamps sorted from oldest to newest. The timeline should show all of them as one list, oldest first.

Write mergeFeeds(a, b) that relinks the nodes of both lists into one sorted list and returns its head. When two timestamps are equal, the node from a comes first.

Example 1

Input: a = [1,2,4], b = [1,3,4]
Output: [1,1,2,3,4,4]

Taking the smaller front post each time gives 1, 1, 2, 3, 4, 4.

Example 2

Input: a = [], b = [0]
Output: [0]

a is empty, so the answer is just b.

Constraints

  • Each list has 0 to 50 nodes.
  • -100 <= node.val <= 100
  • Both lists are sorted ascending.

Lists are written as arrays here, like [1, 2, 3]. Your function works with ListNode objects, each with val and next.

Saved in this browser

Run tries your code on the examples. Submit runs every test, including hidden edge cases, and solves the problem when they all pass.

Ctrl + Enter runs, Ctrl + Shift + Enter submits (⌘ on a Mac).