Implement an In-Memory File Storage System
InstacartSoftware Engineer · Online AssessmentLast updated
This question evaluates the ability to design and implement efficient in-memory data structures and algorithms for stateful file management, covering string-keyed storage, size accounting, querying and sorting, and user quota enforcement.
Implement an in-memory file storage service.
You need to support files identified by a unique full path string, such as "/docs/a.txt". Each file has an integer size and is owned either by the built-in admin user or by a normal user. Directories do not need to be stored separately; treat paths as plain strings.
Design a class that supports the following operations:
addFile(name: string, size: int) -> bool
- Adds a new admin-owned file with path
nameand file sizesize. - Return
trueif the file did not already exist and was added. - Return
falseif a file with the same name already exists.
copyFile(source: string, destination: string) -> bool
- Copies the file at
sourceto a new pathdestination. - The copied file has the same size and owner as the source file.
- Return
trueifsourceexists anddestinationdoes not already exist. - Return
falseotherwise.
getFileSize(name: string) -> int
- Return the size of the file named
name. - Return
-1if the file does not exist.
findFiles(prefix: string, suffix: string) -> list[string]
- Return all files whose names start with
prefixand end withsuffix. - Each result should be formatted as
"<name>(<size>)", for example"/docs/a.txt(120)". - Sort results by size in descending order. If two files have the same size, sort by file name in lexicographical order.
addUser(userId: string, capacity: int) -> bool
- Adds a new user with maximum storage capacity
capacity. - Return
trueif the user did not already exist. - Return
falseotherwise.
addFileByUser(userId: string, name: string, size: int) -> int
- Adds a new file owned by
userId. - The file can be added only if the user exists, the file name does not already exist, and the user's used storage plus
sizedoes not exceed their capacity. - Return the user's remaining capacity after the file is added.
- Return
-1if the operation fails.
updateUserCapacity(userId: string, newCapacity: int) -> int
- Updates the capacity of an existing user.
- If the user's current used storage exceeds
newCapacity, remove that user's files until their used storage is at mostnewCapacity. - When removing files, remove the largest files first; if there is a tie, remove the lexicographically largest file name first.
- Return the number of files removed.
- Return
-1if the user does not exist.
Assume all operations are performed in memory. Choose appropriate data structures and implement the APIs efficiently.
Solution walkthrough is for members
Get the full walkthrough with reference code and complexity analysis, plus Kitty Coach at 300 messages a day. Hints, the code runner and community answers stay free.