KatInterview

Identify Redundant Files by Content Matching

Arrays & HashingAuto-graded · 20 test cases
EasyAuto-gradedArrays & Hashingarrayshash mapstrings

Last 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.