Write a function that removes duplicates from a list while preserving the first occurrence order.
Answer
Use a set to remember values already seen and a list for ordered output. For each item, append it only when it is not already in the set, then add it to the set. This keeps the original first-occurrence order while giving average O(1) membership checks, so the whole pass is O(n) on average rather than repeatedly scanning the output list.
Strong answer includes
- uses a set for average O(1) membership checks
- preserves the first occurrence order
- single pass with O(n) average time
Practical example
Python
Result
Run the code to see the result.
seen provides fast membership checks while result preserves insertion order. This version assumes the input values are hashable.
Expected result: [3, 1, 2, 4]