Design In-Memory File System

HardDesigntrie

Solve this the way you would in the interview: out loud, on a timer, with an AI interviewer asking follow-ups while you code. You get a scored report at the end.

Practice this as a mock interviewFree to start, no account needed

Problem

Implement an in-memory FileSystem with absolute, /-separated paths such as "/docs/notes". The root is "/", and no other path ends with a slash. It starts with an empty root directory. - ls(path): if path is a file, return a list containing just that file's name. If it is a directory, return the names of its direct children (files and directories) sorted in lexicographic order. - mkdir(path): create the directory path, creating any missing parent directories. Existing directories are left alone. - addContentToFile(filePath, content): if the file does not exist, create it (along with any missing parent directories) holding content; otherwise **append** content to what it already holds. - readContentFromFile(filePath): return the file's full content. All paths passed to ls and readContentFromFile exist, and no operation ever tries to treat a file as a directory or a directory as a file.

Examples

Input: ["FileSystem","mkdir","addContentToFile","ls","addContentToFile","readContentFromFile","ls","ls"] [[],["/docs/notes"],["/docs/todo","buy"],["/docs"],["/docs/todo","milk"],["/docs/todo"],["/docs/todo"],["/"]]
Output: [null,null,null,["notes","todo"],null,"buymilk",["todo"],["docs"]]
"/docs" holds the directory "notes" and the file "todo". Appending "milk" makes the content "buymilk". Listing a file returns just its name, and the root contains only "docs".
Input: ["FileSystem","ls","addContentToFile","ls","ls","mkdir","ls"] [[],["/"],["/x/y/z","q"],["/x"],["/x/y"],["/x/a"],["/x"]]
Output: [null,[],null,["y"],["z"],null,["a","y"]]
Creating "/x/y/z" also creates directories "/x" and "/x/y". After adding "/x/a", "/x" lists "a" before "y".

Constraints

  • 1 <= path.length, filePath.length <= 100
  • Paths are absolute; names consist of lowercase letters and are never empty
  • 1 <= content.length <= 50, lowercase letters
  • At most 300 calls in total

What the interviewer grades

A correct solution is one of five scores. The report also grades problem understanding (did you clarify inputs and edge cases before coding), problem solving, communication while you work, code quality, and testing. See a sample report, or read up on the pattern in the lessons.

More trie problems