File System Simulator - Problem

Design and implement a File System Simulator that supports basic file system operations. Your simulator should handle directories and files with the following commands:

Commands to implement:

  • mkdir <path> - Create a directory at the given path
  • touch <path> - Create a file at the given path
  • ls <path> - List contents of a directory (return sorted list)
  • cd <path> - Change current working directory
  • pwd - Print current working directory path

Your implementation should:

  • Start with root directory / as current directory
  • Support both absolute paths (starting with /) and relative paths
  • Handle .. to go up one directory level
  • Return appropriate responses for each command

Note: For this problem, assume all paths are valid and operations are legal (no error handling required).

Input & Output

Example 1 — Basic Operations
$ Input: commands = ["mkdir home", "cd home", "pwd", "touch file.txt", "ls"]
Output: ["/home", ["file.txt"]]
💡 Note: Create 'home' directory, navigate to it, print path '/home', create 'file.txt', and list contents showing ['file.txt']
Example 2 — Nested Directories
$ Input: commands = ["mkdir /docs", "mkdir /docs/projects", "ls /docs", "cd /docs/projects", "pwd"]
Output: [["projects"], "/docs/projects"]
💡 Note: Create nested directories, list '/docs' showing ['projects'], then navigate and show current path
Example 3 — Mixed Content
$ Input: commands = ["mkdir folder", "touch file1.txt", "touch file2.txt", "ls"]
Output: [["file1.txt", "file2.txt", "folder"]]
💡 Note: Create mixed files and directory, then list shows all contents sorted alphabetically

Constraints

  • 1 ≤ commands.length ≤ 100
  • Each command is one of: mkdir, touch, ls, cd, pwd
  • All paths are valid and operations are legal
  • Path names contain only alphanumeric characters and dots

Visualization

Tap to expand
INPUT COMMANDSTREE NAVIGATIONOUTPUT RESULTSmkdir homecd homepwdtouch file.txtls/homefile.txt1234Create home nodeNavigate to homeGet current pathAdd file node"/home"["file.txt"]pwd result:ls result:Key Insight:Tree structure with parent-child node references enables O(depth) navigationinstead of O(n) linear path searches, making file operations much faster.TutorialsPoint - File System Simulator | Tree Structure with Node Objects
Asked in
Google 35 Amazon 28 Microsoft 22 Meta 18
34.2K Views
Medium Frequency
~25 min Avg. Time
856 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen