Union of two sorted arrays

Pattern: Two pointers

medium

Walk both sorted arrays together, always taking the smaller front value and skipping it if it equals the last value added.

The problem

You are given two arrays, each sorted in non-decreasing order, possibly with repeats. Return their union: every value that appears in either array, once each, in increasing order. For example, the union of [1, 2, 3, 4, 5] and [1, 2, 7] is [1, 2, 3, 4, 5, 7].

On the original site the problem is written a little differently, so use the link above for its exact wording. The function name unionArray is this guide's own.

Think first

  • Both arrays are sorted. Which value must come first in the answer?
  • After taking a value, how do you avoid adding it again when it appears in the other array, or repeats in the same one?
  • What do you do when one array runs out?

Hints

    Brute force, and why it fails

    Put every value of both arrays into a set and sort it: O((n + m) log(n + m)). It is correct, but it ignores that the inputs are already sorted. The merge walk is O(n + m).

    The key insight

    Sorted inputs merge in one pass, and the merged stream is sorted too, so duplicates always arrive side by side. One check against the last added value removes them all.

    Dry run

    10i
    11 
    22 
    j0
    result[1]

    a = [1, 1, 2] and b = [2, 3]. Compare the fronts. 1 is not bigger than 2, so take 1 from a.

    Step 1 of 4

    The plan

    result = empty list
    i = 0, j = 0
    while i < len(a) or j < len(b):
        if j == len(b) or (i < len(a) and a[i] <= b[j]):
            next = a[i];  i = i + 1
        else:
            next = b[j];  j = j + 1
        if result is empty or last of result != next:
            append next to result
    return result
    

    Complexity

    Time
    O(n + m)
    Space
    O(n + m)

    Each value is looked at once. The result can hold up to n + m values.

    Edge cases

    • One array empty: the union is the other array without repeats.
    • Identical arrays: each value once.
    • No common values: every value of both, in order.
    I've built my logic, show the code

    Java

    import java.util.*;
    
    class Solution {
        public List<Integer> unionArray(int[] a, int[] b) {
            List<Integer> result = new ArrayList<>();
            int i = 0;
            int j = 0;
            while (i < a.length || j < b.length) {
                int next;
                if (j == b.length || (i < a.length && a[i] <= b[j])) {
                    next = a[i++];                  // take the smaller front value
                } else {
                    next = b[j++];
                }
                if (result.isEmpty() || result.get(result.size() - 1) != next) {
                    result.add(next);               // skip values already added
                }
            }
            return result;
        }
    }

    C++

    class Solution {
    public:
        vector<int> unionArray(vector<int>& a, vector<int>& b) {
            vector<int> result;
            size_t i = 0;
            size_t j = 0;
            while (i < a.size() || j < b.size()) {
                int next;
                if (j == b.size() || (i < a.size() && a[i] <= b[j])) {
                    next = a[i++];                  // take the smaller front value
                } else {
                    next = b[j++];
                }
                if (result.empty() || result.back() != next) {
                    result.push_back(next);         // skip values already added
                }
            }
            return result;
        }
    };

    Python

    class Solution:
        def unionArray(self, a, b):
            result = []
            i = j = 0
            while i < len(a) or j < len(b):
                if j == len(b) or (i < len(a) and a[i] <= b[j]):
                    nxt = a[i]                      # take the smaller front value
                    i += 1
                else:
                    nxt = b[j]
                    j += 1
                if not result or result[-1] != nxt:
                    result.append(nxt)              # skip values already added
            return result

    Common mistakes

    • Checking for repeats only within one array, so a value that appears in both is added twice.
    • Stopping when the shorter array runs out and dropping the rest of the longer one.
    • Sorting the combined arrays, which is slower than needed.

    Similar problems