Learner Level

Implement the mergeTwoSortedArrays method that merges two sorted arrays into one sorted result array.

The input contains two sorted integer arrays nums1 and nums2, along with their lengths size1 and size2. Your task is to merge both arrays into one sorted array.

The returned array must contain all values from both arrays in ascending order. For example, [1,3,5] and [2,4,6] should produce [1,2,3,4,5,6].

Example 1
Input:
nums1 (int[]) = [1,3,5]
size1 (int) = 3
nums2 (int[]) = [2,4,6]
size2 (int) = 3
Return:
(int[]) [1,2,3,4,5,6]
Example 2
Input:
nums1 (int[]) = [1,2]
size1 (int) = 2
nums2 (int[]) = []
size2 (int) = 0
Return:
(int[]) [1,2]
Example 3
Input:
nums1 (int[]) = [-3,4]
size1 (int) = 2
nums2 (int[]) = [-2,0,5]
size2 (int) = 3
Return:
(int[]) [-3,-2,0,4,5]

Use two pointers, one for each sorted array.

Compare the current values from both arrays and append the smaller value to the result. Move the pointer of the array from which the value was taken. After one array is finished, append the remaining values from the other array.

Pseudocode:

function mergeTwoSortedArrays(nums1, size1, nums2, size2):
    i = 0
    j = 0
    result = empty array
    while i < size1 and j < size2:
        if nums1[i] <= nums2[j]:
            add nums1[i] to result
            i++
        else:
            add nums2[j] to result
            j++
    while i < size1:
        add nums1[i] to result
        i++
    while j < size2:
        add nums2[j] to result
        j++
    return result
Run your code to see the result.