Skip to main content

Remove duplicates from a list of email addresses and keep the order in which each address first appeared. For example, a@x.com, b@x.com, a@x.com, c@x.com becomes a@x.com, b@x.com, c@x.com.

Coding rounds · Beginner 3

Short answer

Use list(dict.fromkeys(emails)). A dict keeps insertion order and ignores repeated keys, so the first occurrence of each item survives. It is O(n) time and O(n) extra memory. A plain set loses the order, and checking membership in a list makes the whole thing O(n squared).

Deeper answer

First clarify the input. Ask whether the items are hashable, such as strings or numbers, or unhashable, such as dicts. Ask whether A@x.com and a@x.com count as the same address, and whether to keep the first or the last occurrence.

For hashable items the one-line answer is list(dict.fromkeys(emails)). Dicts have kept insertion order since Python 3.7, so the result keeps first-seen order. The explicit version uses a seen set and an output list: loop over the items, and when an item is not in seen, add it to seen and append it to the output. Use this version when you need a key, such as email.strip().lower(), or when the rows are dicts and you deduplicate on row["id"].

Both are O(n) time and O(n) memory, because set and dict lookups are O(1) on average. Test an empty list, a list with no duplicates, and all items the same. Say out loud why list(set(emails)) is wrong here: a set does not keep order.

What a strong answer covers

Answer it out loud in the mock interview about 2 min

Follow-ups to expect

Common mistakes

Learn it

Lists and dictionaries

Practice Coding rounds questions

More on this topic

Today's AI turns are used

Lessons, roadmaps, videos, practice cards and the code playground stay free with your account, with no limit.