Design In-Memory File System

Understand and solve the interview question "Design In-Memory File System".


You have to design an in-memory file system. The skeleton for the class FileSystem is provided to you. You have to simulate the following functions:

ls: You are given a string representing a path. If it is a file path, return an array that only contains the file’s name. If it is a directory path, return the array of file and directory names in this directory. Your function should return the output (file and directory names together) in lexicographical order.

mkdir: Given a directory path that does not exist, you need to make a new directory according to the path. The function should create all the middle directories in the path if they do not already exist. This function return type is void.

addContentToFile: You are given a file path and file content in string format. If the file doesn’t exist, you need to create that file containing the given content. If the file already exists, you need to append the given content to the original content. This function return type is void.

readContentFromFile: Given a file path, return its content in string format.


Let’s look at an example input and output chart:

Operation Output Explanation
FileSystem fs null The constructor call returns nothing."/") [] Initially, the directory / has nothing. So, we return an empty array.
fs.mkdir("/dir1/dir2/dir3") null Create a directory dir1 in /. Then, create a directory dir2 in directory dir1. Lastly, create a directory dir3 in directory dir2.
fs.addContentToFile("/dir1/dir2/dir3/file1", "File") null Create a file file1 with contents File in the directory /dir1/dir2/dir3."/") [“dir1”] Only directory dir1 exists in the / directory.
fs.readContentFromFile("/dir1/dir2/dir3/file1") “File” Output the file content.


  1. You can assume all file or directory paths are absolute paths that begin with /, and do not end with / except the path that is just "/".

  2. You can assume that all operations will be passed using valid parameters. Users will not attempt to retrieve file content or array a non-existent directory or file or add a non-existent directory file.

  3. You can assume that all directory and file names only contain lower-case letters, and the file and directory names are unique.

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