Problem · Design

Design In-Memory File System

Learn this problem
HardSnowflake logoSnowflakeFULLTIMEPHONE SCREEN
See Snowflake hiring insights

Problem statement

Implement an in-memory file system and execute an ordered array of operations. The file system initially contains only the root directory /.

Each operation is a string array in one of these forms:

  • ["ls", path]: if path is a file, return a one-element row containing its filename. If it is a directory, return the names of its immediate files and directories in lexicographic order.
  • ["mkdir", path]: create every missing directory along path. Existing directories are unchanged.
  • ["addContentToFile", filePath, content]: create the file with content when it does not exist; otherwise append content to the existing file.
  • ["readContentFromFile", filePath]: return a one-element row containing the file's complete content.

Only ls and readContentFromFile produce output rows. Return those rows in operation order. All paths are absolute. Every operation is valid when it runs: parent directories exist where required, directory operations target directories, and file operations target files.

Function

executeFileSystem(operations: String[][]) → String[][]

Examples

Example 1

operations = [["ls","/"],["mkdir","/a/b/c"],["addContentToFile","/a/b/c/d","hello"],["ls","/"],["readContentFromFile","/a/b/c/d"]]return = [[],["a"],["hello"]]

The first root listing is empty. Creating /a/b/c makes a visible at the root, and the final read returns the content stored in file d.

Example 2

operations = [["mkdir","/work/logs"],["addContentToFile","/work/logs/run","hello"],["addContentToFile","/work/logs/run"," world"],["mkdir","/work/cache"],["ls","/work"],["ls","/work/logs/run"],["readContentFromFile","/work/logs/run"]]return = [["cache","logs"],["run"],["hello world"]]

The directory listing is sorted, listing a file returns only its own name, and the second write appends to the existing content.

Constraints

  • 1 <= operations.length <= 2000
  • Paths are absolute, begin with /, contain no repeated slash, and have no trailing slash except for /.
  • Each path component contains 1 to 30 lowercase English letters.
  • Each content string contains at most 1000 lowercase English letters or spaces.
  • The total length of all operation strings is at most 200000.
  • No path is used as both a file and a directory.
  • Every operation satisfies the validity rules in the statement.

More Snowflake problems

drafts saved locally
public String[][] executeFileSystem(String[][] operations) {
    // Write your solution here
}
operations[["ls","/"],["mkdir","/a/b/c"],["addContentToFile","/a/b/c/d","hello"],["ls","/"],["readContentFromFile","/a/b/c/d"]]
expected[[], ["a"], ["hello"]]
checking account