Learner Level

Implement the mergeSortedWithoutDuplicates method that merges two sorted arrays while removing duplicate values.

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 without duplicate values.

For example, merging [1,2,2,4] and [2,3,4] should produce [1,2,3,4].

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

Use two pointers to merge the arrays in sorted order.

Compare the current values from both arrays and take the smaller one. When both values are equal, take it only once and move both pointers. Before adding a value to the result, check whether it is different from the last inserted value.

After one array is finished, add the remaining values from the other array while still skipping duplicates.

Pseudocode:

function mergeSortedWithoutDuplicates(nums1, size1, nums2, size2):
    i = 0
    j = 0
    result = empty list
    while i < size1 and j < size2:
        if nums1[i] < nums2[j]:
            addIfNew(result, nums1[i])
            i++
        else if nums2[j] < nums1[i]:
            addIfNew(result, nums2[j])
            j++
        else:
            addIfNew(result, nums1[i])
            i++
            j++
    while i < size1:
        addIfNew(result, nums1[i])
        i++
    while j < size2:
        addIfNew(result, nums2[j])
        j++
    return result
function addIfNew(result, value):
    if result is empty or last value in result != value:
        add value to result
Run your code to see the result.