easy +8 pts

Difference of Two Lists

Compute the asymmetric difference between two lists while preserving order and multiplicity.

Write a function `difference(a, b)` that takes two lists of integers and returns a new list containing all elements from `a` that are not present in `b`. The result must preserve the original order of elements from `a` and must include duplicates exactly as they appear in `a`. Elements that appear in `b` are removed entirely; the count in `b` does not matter. For example, if `a = [1, 2, 2, 3]` and `b = [2]`, then the result is `[1, 3]` because every occurrence of `2` in `a` is removed. If `b = [2, 2, 2]`, the result is still `[1, 3]`. The function should handle empty lists: if `a` is empty, return `[]`; if `b` is empty, return a copy of `a`.

Constraints

- Input lists may contain any integers (negative, zero, positive). - Lists can have up to 10^5 elements. - The result must be a list of integers. - The function should have O(n + m) time complexity where n = len(a) and m = len(b).

Example

```python
>>> difference([1, 2, 2, 3], [2])
[1, 3]
>>> difference([4, 5, 6], [4])
[5, 6]
>>> difference([1, 2, 3], [])
[1, 2, 3]
>>> difference([], [1, 2])
[]
```
8 points ~10 min

Recent Submissions

No submissions yet — hit Run Tests to try!

Hints

Convert list b to a set for fast membership testing.
Iterate over a and include an element only if it is not in the set.
No need to count occurrences in b — presence is enough.
Python 3
All tests passed!
Test Results
Press Ctrl+Enter or click Run Tests to execute your code.