DSA interview question
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].
vector<int> sortedUnion(const vector<int>& a, const vector<int>& b); // distinct values, sorted
Input (a, b) | Output | Explanation |
|---|---|---|
([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.)
set?"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 interviewAll 474 dsa interview questions
DSA mock interviews · System design interview questions · Free mock interview practice · Browse interviewers · Sign in