KatInterview

Combine Two Ordered Sequences

Arrays & HashingAuto-graded · 16 test cases
EasyAuto-gradedArrays & Hashingtwo-pointerssortingmerge

Last updated

Tests your ability to merge two pre-sorted arrays into a single sorted result using the classic two-pointer technique.

Combine Two Ordered Sequences

You receive two arrays, each already sorted in ascending order. Your task is to produce a single array containing all elements from both inputs, maintaining sorted order.

Write a function that takes two sorted integer arrays and returns a new sorted array containing every element from both inputs.

Constraints

  • Each input array contains between 0 and 50 elements (inclusive)
  • All element values are integers in the range [-100, 100]
  • Both input arrays are sorted in non-decreasing order
  • When both arrays contain equal values, preserve elements from the first array before elements from the second array in the output

Examples

Example 1

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

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

Example 2

Input: combine_sorted_arrays([], [0])

Output: [0]

Hints

Hint 1

Since both arrays are already sorted, you only need to compare the current front elements of each array to find the next smallest overall element.

Hint 2

Use two index pointers to track your position in each input array, advancing whichever pointer points to the smaller current element.

Hint 3

Once you exhaust one array, all remaining elements in the other array are already in sorted order and can be appended directly.