Design In-Memory File System

Try to solve the Design In-Memory File System problem.


Design an in-memory file system by implementing a struct, FileSystem, which should provide the following functionalities:

  • Init(): Initializes the object of the system.

  • Void Ls(String path): If path is a file path, return a list that only contains the file’s name. If it’s a directory path, return the list of files and directory names in this directory. Your function should return the output (file and directory names together) in lexicographical order.

  • Void Mkdir(String path): If the given path does not exist, make a new directory according to it. The function should create all the middle directories in the path if they don’t exist.

  • Void AddContentToFile(String filePath, String content): If the file doesn’t exist, create that file containing the given content. If the file already exists, append the given content to the original content.

  • Void ReadContentFromFile(String filePath): Return given file’s content in string format.

Note: You may assume that all directory names and file names only contain lowercase letters, and the same names will not exist in the same directory. Additionally, you may assume that all operations will be passed valid parameters, and an attempt to retrieve file content or list a directory or file that does not exist is not allowed.


  • 11 \leq path.length, filePath.length \leq 100100

  • path and filePath are absolute paths that begin with “/” and do not end with “/” except that the path is just “/”.

  • 11 \leq content.length 50\leq 50

  • At most 300300 calls will be made to Ls, Mkdir, AddContentToFile, and ReadContentFromFile.

Level up your interview prep. Join Educative to access 70+ hands-on prep courses.