Build a Task Registry and Content-Based Duplicate Finder
Data Structure DesignModel answerLast updated
Design an in-memory task manager with per-user quotas, priority ordering and audit trails, then detect duplicate files using size filtering and streaming hashes.
Context
This is a two-part screen that mixes data-structure design with a practical filesystem task. You will implement two small components in Python. Be explicit about the invariants you maintain and about the assumptions you make where the spec is silent — state them out loud before you start coding.
Part A: Task Registry
Write a TaskManager class that manages tasks belonging to many users. Every task carries:
id— a unique integer assigned by the manageruser_id— the ownerpriority— an integer from 1 to 10status— either'pending'or'completed'
Required methods:
add_task(user_id, priority)— create a task with a fresh unique id and store it. A user may hold at most 5 tasks that are not yet completed; a sixth attempt must be rejected with an error. Priorities outside 1–10 must be rejected.list_tasks(user_id)— return that user's tasks ordered by priority, highest first. Ties must be broken deterministically.get_history(task_id)— return the chronological audit trail of status transitions for one task, including the initial creation event.
You may add whatever supporting methods the design needs (for example, something that marks a task complete) — just explain why they are necessary.
Part B: Duplicate File Detection
Given a root directory path, return groups of files whose contents are byte-identical. You have a helper compute_hash(file_path) that streams a file and returns a string digest.
Example:
tm = TaskManager()
tm.add_task("u1", 5)
tm.list_tasks("u1") # tasks for u1, priority descending
# Input: "/root_dir"
# Output: [["/root_dir/a.txt", "/root_dir/sub/b.txt"], ["/root_dir/c.png"]]
In the example the third group contains a single file. Treat the "list every group" behavior and the "only groups with 2+ files" behavior as a switchable option, and say which one you consider the default.
Constraints
- Registry operations should scale logarithmically or better in the number of tasks.
- The duplicate scan must be careful with memory: never load a whole file into RAM, and avoid hashing files you do not need to.
- Handle unreadable entries, symlinks, and files disappearing mid-scan without crashing.
Hints
Hint 1
The registry spec never says how a task becomes completed — add that method yourself and make the quota counter move on exactly that transition, and only once.
Hint 2
To get priority-descending order with stable ties, store tuples of the form (-priority, id) in a sorted list rather than re-sorting on every read.
Hint 3
Two files with different byte sizes can never be identical, so group by size with a single stat call per file and hash only the buckets that contain two or more paths.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
This problem has two halves. Part A is about turning a loose contract into a class with explicit invariants; Part B is about scanning a filesystem without wasting I/O. Before writing code, I'd clarify two gaps in the spec: there must be a way to complete a task (otherwise the audit log and quota are meaningless), and list_tasks should probably return every task for the user, not just active ones, with ties broken by creation order. I'd also confirm whether the duplicate output should include singleton groups — I treat "only groups of 2 or more" as the default and keep singletons behind a flag.
Part A: Task registry
Three structures do the work:
tasks: dict[task_id -> Task]— O(1) lookup for completing a task or reading its history.by_user: dict[user_id -> list[(-priority, task_id)]]— kept sorted withbisect.insort. Because the sort key starts with the negated priority, ascending order on the key is descending order on priority, and the task id breaks ties in creation order, so output is deterministic.active: dict[user_id -> int]— the number of not-yet-completed tasks, making the quota check O(1).
Each task owns an append-only history list of (sequence, old_status, new_status) tuples. Creation logs (seq, None, 'pending'); completion logs (seq, 'pending', 'completed'). The sequence number comes from a monotonic counter, so events from different tasks can be merged into a global timeline later if needed.
Correctness arguments:
- Unique ids: a single
itertools.countissues ids that are never reused. - Quota integrity:
activeincrements only after validation succeeds inadd_task, and decrements only on thepending -> completedtransition. Completing a task twice raises, so the counter cannot drift below zero or double-decrement. - Ordering invariant:
by_useris always sorted by(-priority, id); every insert and every read depends on this.
Complexity: add_task is O(log k) to locate the insertion point plus O(k) for the list shift worth calling out to the interviewer. If k can be large, swap the list for a balanced tree or sortedcontainers.SortedList to get true O(log k). complete_task is O(1), list_tasks is O(k) since it is bounded by the output, and get_history is O(h).
Edge cases to voice: priority 0 or a string, unknown or already-completed task ids, a user at quota who completes one task and can then add again, and a user who has never been seen (return [], and avoid creating an empty bucket on read).
Part B: Duplicate detection
The naive approach — hash every file and group by digest — is correct but reads the entire tree. The key observation is that identical files must have identical lengths, so length is a free pre-filter obtainable from a single stat call without opening anything.
Algorithm:
- Walk with
os.walk(root, followlinks=False). For each entry, skip symlinks,statit (catchingOSErrorfor unreadable or vanished files), and append the path toby_size[size]. - Discard every size bucket with a single member — those files cannot have a duplicate. If the "include singletons" flag is set, emit them directly as one-element groups.
- For each surviving bucket, call
compute_hash(path), catchingOSErrorper file, and group paths by digest. - Emit groups with two or more paths, or single-element groups when the flag is set.
Correctness: no false negatives, because equal content implies equal size, so duplicates always share a bucket and then share a digest. False positives can only come from a hash collision, which is negligible with SHA-256; if the caller demands exactness, follow up with a byte-wise comparison inside each digest group (and only there).
Memory and time: memory is O(F) for paths plus one fixed-size chunk for whichever file is currently being hashed — that is why compute_hash must read in chunks rather than calling f.read() with no argument. Time is O(F) stat calls plus hashing of only the bytes in colliding buckets, which in practice is a small fraction of the tree. A further refinement for buckets that are large and whose first bytes are identical (many logs starting with the same header) is a cheap prefix hash of the first 4 KB as a second filter before the full hash.
Edge cases: empty directory; unreadable subdirectories (os.walk accepts an onerror hook, or just let permission errors on stat be caught); symlinks skipped to avoid cycles and double-counting; many zero-byte files, all legitimately identical; and files deleted between the walk and the hash — catch OSError and drop them from their group.
Reference implementation
import bisect, hashlib, itertools, os
from collections import defaultdict
from dataclasses import dataclass, field
MAX_ACTIVE = 5
PENDING, COMPLETED = "pending", "completed"
class QuotaExceeded(ValueError):
pass
@dataclass
class Task:
id: int
user_id: str
priority: int
status: str = PENDING
history: list = field(default_factory=list)
class TaskManager:
def __init__(self):
self._ids = itertools.count(1)
self._seq = itertools.count(1)
self._tasks = {}
self._by_user = defaultdict(list) # user -> sorted [(-priority, id)]
self._active = defaultdict(int)
def add_task(self, user_id, priority):
if not isinstance(priority, int) or not 1 <= priority <= 10:
raise ValueError("priority must be an int in 1..10")
if self._active[user_id] >= MAX_ACTIVE:
raise QuotaExceeded(f"{user_id} already has {MAX_ACTIVE} active tasks")
tid = next(self._ids)
task = Task(tid, user_id, priority)
task.history.append((next(self._seq), None, PENDING))
self._tasks[tid] = task
bisect.insort(self._by_user[user_id], (-priority, tid))
self._active[user_id] += 1
return tid
def complete_task(self, task_id):
task = self._get(task_id)
if task.status == COMPLETED:
raise ValueError(f"task {task_id} is already completed")
task.history.append((next(self._seq), task.status, COMPLETED))
task.status = COMPLETED
self._active[task.user_id] -= 1
def list_tasks(self, user_id):
return [self._tasks[tid] for _, tid in self._by_user.get(user_id, [])]
def get_history(self, task_id):
return list(self._get(task_id).history)
def _get(self, task_id):
if task_id not in self._tasks:
raise KeyError(f"unknown task {task_id}")
return self._tasks[task_id]
def find_duplicates(root, include_unique=False):
by_size = defaultdict(list)
for dirpath, _dirs, files in os.walk(root, followlinks=False):
for name in files:
path = os.path.join(dirpath, name)
try:
if os.path.islink(path):
continue
size = os.stat(path).st_size
except OSError:
continue
by_size[size].append(path)
groups = []
for paths in by_size.values():
if len(paths) == 1:
if include_unique:
groups.append(paths)
continue
by_hash = defaultdict(list)
for path in paths:
try:
by_hash[compute_hash(path)].append(path) # provided streaming helper
except OSError:
continue
for digests in by_hash.values():
if len(digests) > 1 or include_unique:
groups.append(digests)
return groups
Common mistakes worth avoiding: re-sorting on every list_tasks call instead of maintaining the order; decrementing the quota on any status change rather than only on completion; hashing every file in the tree; calling read() without a size argument; and forgetting that a byte-wise verification step is the correct way to eliminate collision risk when exactness matters.