765. Dataset hygiene: find duplicate files across train, val and test
You scraped a text dataset and split it into train, val and test folders. Before training you must find files with identical content: a sentence that sits in both train and test makes your test score look better than the model really is (test-set leakage), and plain duplicates waste disk and training time.
Write find_duplicates(tree). tree is a nested dict standing for the root directory: a value that is a dict is a subdirectory, and a value that is a string is a file whose content is that string. A file's path is '/' followed by the names on the way down joined by '/', for example '/train/0001.txt'.
Return a list of groups. Each group is a sorted list of the paths of two or more files with exactly the same content.
Rules:
- Exact match only. 'Cat on a mat' and 'cat on a mat' are different files.
- Empty files (content '') are ignored. A file holding only a space ' ' is not empty, so it counts.
- Two files can share a name in different folders and still differ in content.
- Empty subdirectories are fine and contribute nothing.
- Sort each group's paths, then sort the groups by their first path.
def find_duplicates(tree)Example 1
Input: tree = {'a.txt': 'hi', 'docs': {'b.txt': 'hi', 'c.txt': 'yo'}, 'd.txt': 'yo', 'e.txt': ''}
Output: [['/a.txt', '/docs/b.txt'], ['/d.txt', '/docs/c.txt']]
Example 2
Input: tree = {'x': {'y': {}}, 'z.txt': 'unique'}
Output: []
Example 3
Input: tree = {'a': {'f': '1'}, 'b': {'f': '2'}, 'c': {'f': '1'}}
Output: [['/a/f', '/c/f']]
Constraints
- At most 10,000 files.
- Names contain no '/'.
- Content is any string.
Hint 1
Recursion with the path so far as an argument keeps paths simple.
Hint 2
A dict from content to a list of paths does the grouping.
Hint 3
Skip empty strings before grouping.
Common mistakes
- Treating an empty directory as a file.
- Returning groups of size one.
- Forgetting to sort the groups and their members.
Understand the idea
Deduplication is a grouping problem: choose a key that equal items share, and bucket by it. Cheap keys first (size), expensive keys later (a content hash), exact comparison last. The same idea scales to removing duplicate documents from training data, where exact hashes catch copies and MinHash catches near copies.