Deduplicate a File In Place

Medium ⏱ 12 min 50% acceptance ★★★★★ 4.7
Write dedupe_file(path) that removes duplicate lines from a text file while preserving first-occurrence order, rewriting the same file, and returning how many duplicates were removed.

Examples

Example 1
Input
dedupe_file('emails.txt')  # a, b, a, c, b
Output
2
Explanation

The second a and second b are removed; file keeps a, b, c.

Constraints

  • Order of first occurrences preserved.
  • Return the removed count.

Topics

File Handlingdedup + rewrite

Companies

FlipkartMeta

Hints

Hint 1

Read all lines first; you cannot read and truncate simultaneously.

Hint 2

A seen-set plus an output list does the filtering.

Loading the Python runtime… Run executes your code and shows printed output; Submit checks your function against this problem's examples.