37 · Design Data Structures

#588 Design In-Memory File System

frequently reported atUberAmazonMicrosoftGoogle

the problem

In plain words

You're writing the storage layer of a small browser-based code editor, and everything lives in memory. Implement FileSystem with four calls. ls(path): for a file, return a list holding just the file's name; for a folder, return the names of everything directly inside it, in alphabetical order. mkdir(path): create that folder, plus any missing folders above it. addContentToFile(filePath, content): create the file if it is new, then append content to it. readContentFromFile(filePath): return everything written to the file so far. Every call is valid: ls and read only ask about paths that exist, mkdir creates a folder that doesn't exist yet, a new file goes into a folder that already exists, and a file and a folder never share a name inside the same folder.

in ls("/"), mkdir("/home/priya/code"), addContentToFile("/home/priya/code/notes", "stack"), addContentToFile("/home/priya/todo", "revise"), ls("/home/priya"), addContentToFile("/home/priya/code/notes", "queue"), readContentFromFile("/home/priya/code/notes"), ls("/home/priya/code/notes"), ls("/")

out [], null, null, null, ["code", "todo"], null, "stackqueue", ["notes"], ["home"]

mkdir created home, priya and code in one call. The second write to notes is appended. ls on a file lists only its own name.

  • Paths are absolute: they start with "/" and don't end with "/" (except "/" itself); 1 ≤ path length ≤ 100
  • Names use lowercase letters only
  • 1 ≤ content length ≤ 50
  • At most 300 calls in total

your turn

Try it before you peek

Read the examples, say the brute force out loud, then write code right here. Stuck for 20 minutes? Open one hint at a time.

This one is LeetCode Premium. You don't need a subscription: solve it right here. The free alternative linked above is the closest free practice; its label says how close it is.

Solve it in the browser

Design: implement every operation. Compiled by the real javac (Java 17) and judged right here — nothing is sent anywhere.

    Solutions are hidden so you can try first. Even 20 minutes of real effort makes the answer stick far better than reading it.

    Marking the problem solved, or opening every hint, also shows it.

    practise next

    Similar problems

    1. #208
    2. #71
      Simplify Path
      Mediumin Stacks
    3. #211