Group Paths Whose File Contents Match Exactly
Arrays & HashingAuto-graded · 17 test casesLast updated
Group file paths whose contents are identical, using cheap filters like size and digest, with an exact comparison to confirm. Output is sorted groups of two or more paths.
You are given an in-memory description of a small file system. Each file is a dictionary with two string fields:
"path": the file's path (unique across the input)."content": the file's full text content.
Write a function that finds every set of files whose contents are exactly equal and returns the paths of those files, grouped by content.
Rules
- Two files are duplicates only if their complete contents are identical, character for character. Matching size, a matching prefix, or a matching hash alone is not enough to count as a duplicate.
- Only report groups with at least two paths. A file whose content is unique must not appear in the output.
- Empty files (content
"") are valid files. Two or more empty files form a duplicate group. - Within each group, sort the paths in ascending lexicographic (string) order.
- Sort the list of groups itself in ascending order, comparing groups as lists of strings (that is, standard list comparison, first element first).
- If no duplicates exist, return an empty list.
Input
files: a list of dictionaries, each with keys"path"and"content", both strings.
Output
A list of groups, where each group is a sorted list of at least two paths that share identical content, and the groups are sorted as described above.
Constraints
- Paths are unique within the input.
- The input list may be empty, in which case the result is an empty list.
- Content may be empty.
- The result must be exact: do not treat a digest match as proof of equality.
- Do not modify the input.
Examples
Example 1
Input: group_identical_files([{'path': 'a.txt', 'content': 'hello'}, {'path': 'b.txt', 'content': 'hello'}, {'path': 'c.txt', 'content': 'world'}])
Output: [['a.txt', 'b.txt']]
Example 2
Input: group_identical_files([{'path': 'empty1', 'content': ''}, {'path': 'empty2', 'content': ''}, {'path': 'x', 'content': 'x'}])
Output: [['empty1', 'empty2']]
Example 3
Input: group_identical_files([{'path': 'z', 'content': 'same'}, {'path': 'a', 'content': 'different'}, {'path': 'm', 'content': 'same'}, {'path': 'b', 'content': 'same'}])
Output: [['b', 'm', 'z']]
Hints
Hint 1
Cheap properties such as length can rule out equality quickly, but they can never confirm it. Think about which grouping key to use first.
Hint 2
Hashing the content narrows down candidates. Within each narrowed bucket, compare the real contents (for example, by using the content itself as a dictionary key) so that a hash collision cannot produce a wrong group.
Hint 3
After grouping, drop groups with fewer than two paths, sort the paths inside each group, and then sort the list of groups.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The goal is to group paths by exact content while avoiding needless full comparisons.
- Cheap filter first. Build a key from the content length and a SHA-256 digest of the content. Files with different lengths or different digests cannot be equal, so they land in different buckets. This reduces the number of pairs that need to be considered.
- Exact verification. A matching digest only suggests equality; it does not prove it. Inside each bucket, regroup the files using the full content as the dictionary key. This guarantees that only files with truly identical content end up together, even in the (astronomically unlikely) case of a hash collision.
- Filter and format. Keep only groups with two or more paths, sort the paths within each group, and then sort the list of groups.
Why it is correct
- Equal contents always produce equal lengths and equal digests, so true duplicates always share a bucket and none are missed.
- The second stage keys on the actual content, so two files are grouped together only if their contents are identical.
- Dropping singleton groups and sorting follows the output rules exactly, which makes the output deterministic.
Complexity
Let n be the number of files and B the total number of bytes across all contents.
- Time:
O(B)for hashing and dictionary lookups on content (hashing a string of lengthLcostsO(L)), plusO(n log n)style sorting of paths and groups (comparisons may cost up to the path length). - Space:
O(B + n)since contents are held in memory in this in-memory formulation. In a real file system you would stream files in bounded chunks, group by size first, and only re-read files within a bucket for the final exact check.
Reference solution
import hashlib
from collections import defaultdict
from typing import List, Dict
def group_identical_files(files: List[Dict[str, str]]) -> List[List[str]]:
# Stage 1: bucket by (length, SHA-256 digest). Cheap filters that can
# only reject equality, never prove it.
buckets = defaultdict(list)
for record in files:
path = record["path"]
content = record["content"]
digest = hashlib.sha256(content.encode("utf-8")).digest()
buckets[(len(content), digest)].append((path, content))
# Stage 2: inside each bucket, group by the actual content so the
# result is exact even if a hash collision occurred.
result = []
for bucket in buckets.values():
by_content = {}
for path, content in bucket:
by_content.setdefault(content, []).append(path)
for paths in by_content.values():
if len(paths) >= 2:
result.append(sorted(paths))
result.sort()
return result