progress

~/problems / Files & networks / File deduplication

Clean up notes synced from two laptops

On a phone? Coding is easier on a laptop: email this problem to yourself . Meanwhile: quiz this topic or fight a boss.

easy ~15 min

Years of syncing notes between a Windows laptop and a Mac left many copies of the same note that differ only in line endings or trailing blank lines. Plan the cleanup.

Implement cleanup_plan(files: dict[str, bytes]) -> dict[str, str] (path to raw contents).

Two notes are the same when their normalized contents match. To normalize, replace every b"\r\n" with b"\n" (a lone b"\r" stays), then strip all trailing b"\n". Trailing spaces are not stripped. So b"", b"\n" and b"\r\n" are the same empty note.

In each group of two or more, keep the shortest path (ties: alphabetically smallest) and map every other path in the group to it. Unique paths and kept paths don't appear.

cleanup_plan({
    "notes/shopping.txt":      b"milk\r\neggs\r\n",
    "mac/notes/shopping.txt":  b"milk\neggs",
    "s.txt":                   b"milk\neggs\n\n",
    "todo.txt":                b"call mum\n",
    "todo copy.txt":           b"call mum \n",   # trailing space: a different note
})
# {"notes/shopping.txt": "s.txt", "mac/notes/shopping.txt": "s.txt"}

⭐ Bonus: comparing every pair still passes; a speed test with 40,000 notes earns a star if you group by a SHA-256 digest of the normalized bytes, as in Basics: group paths by identical content.

Show hint

data.replace(b"\r\n", b"\n").rstrip(b"\n") normalizes; pick keepers with min(paths, key=lambda p: (len(p), p)).

Topic: File deduplication. Group by size, then hash; walk directories.

Read the visual guide
0:00
Ctrl ' run · Ctrl ↵ submit
esc