cppintermediate10 minutes

Create a Function to Merge Two Sorted Arrays Without Duplicates

Build a C++ function that takes two sorted integer arrays and returns a new sorted array containing all unique elements from both arrays, effectively merging them without duplicates.

Challenge prompt

Write a function named mergeSortedUnique that accepts two vectors of integers (both sorted in ascending order) and returns a single vector sorted in ascending order containing all unique elements from both input vectors. The output vector should not contain any duplicate elements even if duplicates exist in the input arrays. You can only use standard C++ libraries.

Guidance

  • Iterate through both vectors simultaneously with two indices to merge them efficiently given they are sorted.
  • Avoid adding duplicates to the resulting vector by comparing the current element with the last element inserted.
  • Handle cases when one array is exhausted before the other.

Hints

  • Use two pointers or indices to traverse the arrays and compare elements.
  • Remember to check if the merged vector is empty before pushing elements to avoid out-of-range errors.
  • Consider edge cases like empty input vectors.

Starter code

std::vector<int> mergeSortedUnique(const std::vector<int>& arr1, const std::vector<int>& arr2) {
    std::vector<int> result;
    // Your code here
    return result;
}

Expected output

[1, 2, 3, 4, 5, 6, 7, 8]

Core concepts

vectorstwo-pointer techniquearraysconditional logic

Challenge a Friend

Send this duel to someone else and see if they can solve it.