← Back to Python, page 4

python-0080 · Easy fresher

Find the duplicate values in a list while keeping the order in which they first repeat.

Walk the list once with a set of values seen so far; when a value is already in the set and not yet reported, record it. This is O(n) time, unlike the O(n squared) approach of calling list.count for every item. Counter works when order does not matter.

Full answer
python
from collections import Counter

def duplicates(items):
    seen, reported, result = set(), set(), []
    for x in items:
        if x in seen and x not in reported:
            result.append(x)
            reported.add(x)
        seen.add(x)
    return result

orders = ["pen", "ink", "pen", "pad", "ink", "pen", "cap"]
print(duplicates(orders))
print(sorted(k for k, v in Counter(orders).items() if v > 1))
print(list(dict.fromkeys(orders)))

Output:

text
['pen', 'ink']
['ink', 'pen']
['pen', 'ink', 'pad', 'cap']

'pen' repeats at position 2 and 'ink' at position 4, so the result lists them in that order, and the third 'pen' is not reported again because of the reported set. The Counter version finds the same values, sorted here for a stable display. dict.fromkeys is the related idiom for removing duplicates while keeping first-seen order, since dicts preserve insertion order. Set membership checks are O(1) on average, which keeps the whole scan linear.

python
from collections import Counter

def duplicates(items):
    seen, reported, result = set(), set(), []
    for x in items:
        if x in seen and x not in reported:
            result.append(x)
            reported.add(x)
        seen.add(x)
    return result

orders = ["pen", "ink", "pen", "pad", "ink", "pen", "cap"]
print(duplicates(orders))
print(sorted(k for k, v in Counter(orders).items() if v > 1))
print(list(dict.fromkeys(orders)))

Run on Python 3.13.5, twice in fresh interpreters, with identical output.

Key points

  • Track seen values in a set
  • O(n) instead of repeated count()
  • Report each duplicate once
  • Counter when order does not matter
  • dict.fromkeys removes duplicates in order

Common mistakes

  • Calling items.count(x) inside a loop
  • Using set() when order matters

Follow-ups

  • How would you find duplicates in a file too big for memory?
  • How would you return counts too?

Tips

  • State the complexity