Identify Redundant Files by Content Matching
Arrays & HashingAuto-graded · 20 test casesLast updated
Cluster files that share identical byte contents by filtering first on file size metadata and then hashing content.
Given a list of file records, find all groups of identical files based on byte-for-byte content matching.
Each file record is represented as a dictionary containing the following keys:
"path": string indicating the path of the file."size": non-negative integer for the size of the file in bytes."content": string (or bytes) containing the payload of the file.
Two files are considered duplicates if their contents are byte-for-byte identical, regardless of their path or directory structure.
Return a list of duplicate groups, where each group is a list of file paths. Do not include files that have no duplicates (groups of size $1$).
Constraints
- $1 \le N \le 10^4$, where $N$ is the number of file records.
"size"is a non-negative integer.- The order of paths within a group and the order of groups in the returned list do not matter.
Examples
Example 1
Input: group_duplicate_files([{'path': '/a/x.txt', 'size': 4, 'content': 'ABCD'}, {'path': '/b/y.txt', 'size': 4, 'content': 'ABCD'}, {'path': '/c/z.txt', 'size': 4, 'content': 'WXYZ'}, {'path': '/d/w.txt', 'size': 7, 'content': '1234567'}])
Output: [['/a/x.txt', '/b/y.txt']]
Example 2
Input: group_duplicate_files([{'path': '/tmp/a', 'size': 3, 'content': 'cat'}, {'path': '/tmp/b', 'size': 3, 'content': 'dog'}, {'path': '/tmp/c', 'size': 3, 'content': 'cat'}, {'path': '/tmp/d', 'size': 4, 'content': 'bird'}, {'path': '/tmp/e', 'size': 4, 'content': 'bird'}])
Output: [['/tmp/a', '/tmp/c'], ['/tmp/d', '/tmp/e']]
Example 3
Input: group_duplicate_files([{'path': '/a', 'size': 0, 'content': ''}, {'path': '/b', 'size': 0, 'content': ''}, {'path': '/c', 'size': 1, 'content': 'x'}])
Output: [['/a', '/b']]
Hints
Hint 1
Try partitioning files by size first to avoid analyzing file content unnecessarily.
Hint 2
Files of distinct sizes can never share identical contents.
Hint 3
Use a map to cluster files by size, then use a cryptographic hash or content key on non-unique size buckets to group identical contents.
Worked solution
Easy Try it yourself first — then compare your approach, complexity and edge cases.
Approach
To efficiently detect duplicate files without unnecessary operations on file contents:
- Size Partitioning: Files of different byte lengths cannot be duplicates. We first group all files by their
sizeproperty using a dictionary. Any size bucket with fewer than two files is discarded immediately. - Content Hash Grouping: For candidate files sharing the same size, we compute a SHA-256 hash of their contents (converting string data to bytes if necessary). We group the paths by their computed digest.
- Filtering Output: Any hash group with two or more paths represents a valid set of duplicates and is appended to the answer list. Singletons are excluded.
Complexity
- Time Complexity: $\mathcal{O}(N + \sum L)$, where $N$ is the number of file dictionaries and $L$ is the byte length of candidate file contents. Size grouping takes $\mathcal{O}(N)$, while content hashing operates in linear time relative to content length.
- Space Complexity: $\mathcal{O}(N + \sum L)$ to store file path mappings and intermediate hash keys.
from typing import List, Dict
from collections import defaultdict
import hashlib
def group_duplicate_files(files: List[Dict[str, object]]) -> List[List[str]]:
# Phase 1: Partition files by file size
size_map = defaultdict(list)
for file in files:
size_map[file['size']].append(file)
result = []
# Phase 2: Hash contents for size groups containing more than one file
for file_list in size_map.values():
if len(file_list) < 2:
continue
content_map = defaultdict(list)
for file in file_list:
content = file['content']
if isinstance(content, str):
content = content.encode('utf-8')
digest = hashlib.sha256(content).hexdigest()
content_map[digest].append(file['path'])
for paths in content_map.values():
if len(paths) > 1:
result.append(paths)
return result