Unix Find Command
medium · tree traversal, composable filters
Brief-reported interview attribution (unverified): Amazon
How to approach an LLD roundImplement the core of the Unix find command over an in-memory
file tree. add_dir creates directories (parents as needed); add_file creates
a file with a size in bytes (parents as needed). find(path, ...) walks the tree
below path and returns every matching path, sorted. Filters combine with AND:
name (exact match on the last component), type ("f" for files, "d" for
directories), size_gt / size_lt (file size in bytes; a size filter never
matches a directory).
class UnixFind:
def __init__(self):
def add_dir(self, path):
# creates all missing directories along the path
def add_file(self, path, size):
# creates the file (parents as needed); -> False for an empty/invalid path
def find(self, path, name=None, type=None, size_gt=None, size_lt=None):
# -> sorted list of absolute paths that match all given filters
# (the starting path itself is included when it matches; [] for a missing path)
Rules. A filter that is None is ignored. size_gt/size_lt are strict
(size > size_gt, size < size_lt). find on a file path returns that file
alone when it matches, and [] when it does not. The root / is a directory
and is included in results when it matches.
Tests use explicit inputs and injected clocks/callbacks. No network, real threads or application-server execution is involved.
Public demo
# Public demo: run after implementing the class API above.
f = UnixFind()
for path, size in [('/a/b/f1.txt', 100), ('/a/b/f2.log', 500), ('/a/c/f3.txt', 50), ('/a/readme.md', 1000), ('/d/x.py', 200)]:
f.add_file(path, size)
print(f.find('/', type='f'))Starter code
class UnixFind:
def __init__(self):
"""Initialize the state described in the problem."""
pass
def add_dir(self, path):
"""creates all missing directories along the path"""
pass
def add_file(self, path, size):
"""creates the file (parents as needed); -> False for an empty/invalid path"""
pass
def find(self, path, name=None, type=None, size_gt=None, size_lt=None):
"""-> sorted list of absolute paths that match all given filters (the starting path itself is included when it matches; [] for a missing path)"""
pass
Each test has a five-second execution limit. Your practice drafts and solved progress stay in this browser.
Return to the Python compiler