PPractick

DSA interview question

Union of Two Sorted Arrays

Easy · Algorithms · Topics: array, two pointer

The problem

Two regional warehouses each send a sorted list of the product IDs they stock, and head office wants a single sorted list of every distinct ID stocked by either warehouse. The lists can each hold a million IDs and may contain repeats. Throwing everything into a set works but costs O((n + m) log(n + m)) and extra memory. Because both inputs are already sorted, a two-pointer merge produces the union in one linear pass, skipping duplicates as it goes. It's the same merge step used in merge sort.

Example: [1, 2, 3, 4, 5] and [1, 2, 3, 6, 7] → [1, 2, 3, 4, 5, 6, 7].

Function signature

vector<int> sortedUnion(const vector<int>& a, const vector<int>& b);  // distinct values, sorted

Test cases

Input (a, b)OutputExplanation
([1, 2, 3, 4, 5], [1, 2, 3, 6, 7])[1, 2, 3, 4, 5, 6, 7]
([2, 2, 3, 4, 5], [1, 1, 2, 3, 4])[1, 2, 3, 4, 5]Duplicates inside each array
([1, 1, 1], [1])[1]
([], [3, 3, 4])[3, 4]One side empty
([-5, 0, 10], [-5, -3, 10, 12])[-5, -3, 0, 10, 12]Negative values

(Confirm: both inputs are sorted in non-decreasing order; the result has no duplicates.)

How interviewers phrase it

Clarifying questions to ask

  1. Are both arrays sorted?
  2. Should the result contain duplicates? (Usually not for a union.)
  3. Can the arrays be empty?
  4. Is extra space for the output fine?

Follow-ups to expect

  1. "Why not use a set?"
  2. "How do you skip duplicates?"
  3. "How would you compute the intersection?"
  4. "What if the arrays were unsorted?"
  5. "Complexity?"

Practise questions like this with a real engineer

On Practick another engineer interviews you live for 60 minutes on a question from this bank. They have the full interviewer guide beside the call: the expected answer to every follow-up, hints to give if you stall, and a scoring rubric. You get the model solution once the session settles. It is free: interview someone for an hour and you have earned your own.

Book a free mock interview

Related questions

All 474 dsa interview questions

DSA mock interviews · System design interview questions · Free mock interview practice · Browse interviewers · Sign in