Remove duplicates, keep order
Write dedupe(items) that removes duplicates from a list while keeping the first occurrence of each item in its original order.
dedupe([3, 1, 3, 2, 1])
# [3, 1, 2]
Show hint
set(items) removes duplicates but loses the order. Since Python 3.7, dictionaries keep insertion order.
Show solution
def dedupe(items):
return list(dict.fromkeys(items))
dict.fromkeys keeps only the first time each key is inserted, and dicts remember insertion order. The long version is a loop with a seen set. Both run in O(n) time and need the items to be hashable.
Want a problem like this every day? See today's problem and keep a streak going.