KatInterview

Combine Two Sorted Sequences

Linked ListsAuto-graded · 22 test cases
EasyAuto-gradedLinked Liststwo-pointerslinked-listarrays

Last updated

Merge two non-decreasing sequences into a single sorted sequence, maintaining stable order on equal values.

Given two non-decreasingly ordered integer sequences l1 and l2, combine all elements into a single non-decreasing sequence.

Whenever an element from l1 is equal to an element from l2, the element from l1 must appear earlier in the resulting sequence.

Constraints

  • The length of both l1 and l2 is between 0 and 50.
  • Element values range between -100 and 100.
  • Both inputs are sorted in non-decreasing order.

Examples

Example 1

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

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

Example 2

Input: merge_two_lists([], [0])

Output: [0]

Hints

Hint 1

Use two pointers to track your current index in each input list.

Hint 2

At each step, compare the current elements of both lists and choose the smaller one.

Hint 3

Use a non-strict inequality (<=) to ensure elements from l1 take precedence when values are equal.

Hint 4

Once one list is exhausted, append all remaining elements from the other list.