KatInterview

Combine Two Ascending Sequences Into One

Linked ListsAuto-graded · 24 test cases
EasyAuto-gradedLinked Liststwo-pointersmergesorting

Last updated

Tests a two-pointer merge of two non-decreasing integer lists into a single sorted list, handling empty inputs and duplicate values correctly.

You are given two integer lists, first and second. Each one is already sorted in non-decreasing order (equal neighbors are allowed). Produce a single list that contains every element from both inputs, also in non-decreasing order.

This is the same operation you would perform when stitching two sorted linked lists together, here expressed on Python lists.

Requirements

  • The result must include all elements of first and all elements of second, with duplicates preserved (nothing is removed or merged).
  • The result must be sorted in non-decreasing order.
  • Either input may be empty. If both are empty, return an empty list.
  • Do not modify the input lists.
  • Aim for a single pass over both inputs rather than concatenating and re-sorting.

Constraints

  • 0 <= len(first), len(second)
  • Both first and second are sorted in non-decreasing order.
  • Elements are integers (negative values and zero are allowed).
  • The return value is a new list of length len(first) + len(second).

Examples

Example 1

Input: merge_two_sorted([1, 2, 4], [1, 3, 4])

Output: [1, 1, 2, 3, 4, 4]

Example 2

Input: merge_two_sorted([], [0])

Output: [0]

Example 3

Input: merge_two_sorted([], [])

Output: []

Example 4

Input: merge_two_sorted([1, 2, 5, 8], [2, 2, 6])

Output: [1, 2, 2, 2, 5, 6, 8]

Hints

Hint 1

Keep one index into each list. At every step, look only at the two elements currently pointed to.

Hint 2

Append the smaller of the two current elements to the output and advance only that list's index. When values are equal, taking from either list gives the same result.

Hint 3

When one list runs out, the rest of the other list is already sorted, so you can append it in one go.