Return values in list A that are missing from list B, preserving A's order, using a set for O(n+m) lookups. Python set difference explained with tests.
The problem
Return the values of a that are not in b, in the order they appear in a, each once.
Examples
Example 1
Input
difference([1, 2, 3, 4, 5], [3, 4, 5, 6, 7])
Expected output
[1, 2]
Example 2
Input
difference([5, 1, 5], [])
Expected output
[5, 1]
+ 2 hidden tests on Submit.
Edge cases to ask about
- b empty
- Everything excluded
- Duplicates in a
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 lookups | O(n × m) | O(1) | Scans b for every element. |
| bestset(b) once | O(n + m) | O(m) | Order-preserving set difference. |
Walkthrough of the optimal approach (try it yourself first)
set(a) - set(b) is the textbook answer but loses order. Build set(b) once and filter a — O(n + m) and order-preserving.
Complexity: O(n + m) time, O(m) space. Building set(b) is O(m); scanning a with O(1) lookups is O(n).
Reveal the reference solution
def difference(a, b): exclude = set(b) seen = set() out = [] for x in a: if x not in exclude and x not in seen: seen.add(x) out.append(x) return out
The brute force, for comparison
def difference(a, b): out = [] for x in a: if x not in b and x not in out: out.append(x) return out
Follow-ups interviewers ask
- Symmetric difference (in exactly one list).
Frequently asked interview questions
Core interview concepts, complexities, and follow-ups scored by hiring teams.
What is the time complexity of Elements in One List but Not Another in Python?
The optimal solution runs in O(n + m) time and O(m) auxiliary space. Building set(b) is O(m); scanning a with O(1) lookups is O(n).
What is the brute-force approach, and how do you optimise it?
List lookups: O(n × m) time, O(1) space. Scans b for every element. set(b) once: O(n + m) time, O(m) space. Order-preserving set difference.
What follow-up questions do interviewers ask about Elements in One List but Not Another?
Symmetric difference (in exactly one list).
