v9.1.1
Menu

Merge Two Sorted Lists

easyPROLinked Lists & PointersApple DSA

Write merge_lists(l1, l2) that merges two sorted lists into one sorted list and returns it as a list. Every element of both inputs must appear in the result (duplicates are kept), and either input may be empty. The tests print the returned list as space-separated values.

Example

Input
1,2,4
1,3,4
Output
1 1 2 3 4 4
Reasoning
  • The inputs are two lists, l1 = [1, 2, 4] and l2 = [1, 3, 4], each already in non-decreasing order. They can have different lengths, and either one can be empty.
  • The output holds every element from both lists exactly once, so its length is 3+3=63 + 3 = 6. Nothing is dropped and nothing is de-duplicated.
  • Count each value across the two inputs: 11 appears once in each list, so twice in total. 22 and 33 appear once each, and 44 appears once in each list, so twice. In non-decreasing order that gives 1≤1≤2≤3≤4≤41 \le 1 \le 2 \le 3 \le 4 \le 4.
  • The function returns that list, [1, 1, 2, 3, 4, 4]. The tests print it with spaces between the values: 1 1 2 3 4 4.
  • Notice that when one input is empty, the result is just the other list, and two empty inputs give an empty list (printed as EMPTY).

Constraints

  • 0 <= number of nodes <= 50
  • -100 <= Node.val <= 100

More from Apple DSA

PRO

Editor locked

The code editor is locked for Pro problems. It is only available for free problems. Please upgrade to gain access to the code editor for all problems.

solution.py

Test results

Sign in to run your code against the test cases.