Check whether two lists contain the same distinct elements regardless of order or repeats using set equality in O(n+m). Learn when to use Counter.
The problem
Return True if a and b contain the same distinct values, ignoring order and how many times each appears.
[1, 2, 3, 3] and [3, 2, 1] → True.
Examples
Example 1
Input
same_elements([1, 2, 3, 3], [3, 2, 1])
Expected output
True
Example 2
Input
same_elements([1, 2], [1, 2, 4])
Expected output
False
+ 3 hidden tests on Submit.
Edge cases to ask about
- Both empty
- Repeated values
- One empty
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 |
|---|---|---|---|
| Sort both distinct lists | O(n log n) | O(n) | |
| bestSet equality | O(n + m) | O(n + m) | Counts are ignored by design; use Counter if they should matter. |
Walkthrough of the optimal approach (try it yourself first)
set(a) == set(b) answers "same distinct values". If the interviewer then says counts matter, switch to Counter(a) == Counter(b) — knowing the difference is the point of the question.
Complexity: O(n + m) time, O(n + m) space. Two sets are built in linear time and compared in O(min(n, m)).
Reveal the reference solution
def same_elements(a, b): return set(a) == set(b)
Follow-ups interviewers ask
- Counts must match too.
- Elements are unhashable (lists).
Frequently asked interview questions
Core interview concepts, complexities, and follow-ups scored by hiring teams.
What is the time complexity of Check Two Lists Have the Same Elements in Python?
The optimal solution runs in O(n + m) time and O(n + m) auxiliary space. Two sets are built in linear time and compared in O(min(n, m)).
What is the brute-force approach, and how do you optimise it?
Sort both distinct lists: O(n log n) time, O(n) space. Set equality: O(n + m) time, O(n + m) space. Counts are ignored by design; use Counter if they should matter.
What follow-up questions do interviewers ask about Check Two Lists Have the Same Elements?
Counts must match too. Elements are unhashable (lists).
