Merge two Python lists into their union with no duplicates and first-seen order preserved. Uses a seen-set for O(n+m) time.
The problem
Return every value that appears in either list, each once, in the order it is first seen (all of list1, then list2).
Examples
Example 1
Input
union([1, 2, 3, 4], [3, 4, 5, 6])
Expected output
[1, 2, 3, 4, 5, 6]
Example 2
Input
union([2, 2], [2, 1])
Expected output
[2, 1]
+ 3 hidden tests on Submit.
Edge cases to ask about
- Both empty
- Fully overlapping lists
- Duplicates inside one list
Hints
0/3How an interviewer scores this
0/9Your code runs in real CPython inside your browser — nothing is sent anywhere. The first run downloads the interpreter (about 6 MB, once). Your code is saved on this device as you type.
Complexity Lab
What does this cost as n grows?
Interviewers score the analysis as much as the code. Commit to an answer first — then check it, and measure your code against the optimal one at growing input sizes.
Pick both to reveal the answer.
Measure it
Runs the function on inputs of size 250 up to 16,000 and records the time and peak memory. Slow solutions stop early — a short curve is itself the answer.
From brute force to optimal
The progression an interviewer wants to hear, one step at a time.
| Approach | Time | Space | Idea |
|---|---|---|---|
| List membership | O((n+m)²) | O(n+m) | Each not in out scans the result. |
| bestSeen set | O(n + m) | O(n + m) | Set lookups are O(1); the list keeps order. |
Walkthrough of the optimal approach (try it yourself first)
Union is just dedupe applied to list1 + list2: keep a seen set, append each value the first time it shows up.
set(a) | set(b) is the one-liner, but it throws away order — say so in the interview and offer both.
Complexity: O(n + m) time, O(n + m) space. Each of the n + m values is visited once with O(1) set operations; the set and output can hold all of them.
Reveal the reference solution
def union(list1, list2): seen = set() out = [] for x in list1 + list2: if x not in seen: seen.add(x) out.append(x) return out
The brute force, for comparison
def union(list1, list2): out = [] for x in list1 + list2: if x not in out: out.append(x) return out
Follow-ups interviewers ask
- Return it sorted.
- Union of k lists.
Frequently asked interview questions
Core interview concepts, complexities, and follow-ups scored by hiring teams.
What is the time complexity of Union of Two Lists Without Duplicates in Python?
The optimal solution runs in O(n + m) time and O(n + m) auxiliary space. Each of the n + m values is visited once with O(1) set operations; the set and output can hold all of them.
What is the brute-force approach, and how do you optimise it?
List membership: O((n+m)²) time, O(n+m) space. Each `not in out` scans the result. Seen set: O(n + m) time, O(n + m) space. Set lookups are O(1); the list keeps order.
What follow-up questions do interviewers ask about Union of Two Lists Without Duplicates?
Return it sorted. Union of k lists.
