Katkat

Print the File System State

Anchorage DigitalSoftware Engineer · Technical Screen

Last updated

This problem tests your ability to recursively traverse a tree structure and format the output into a specific, ordered directory-style string representation.

Problem Statement

You are given a representation of a file system as a list of file and directory paths. A directory can contain files or subdirectories. Your task is to implement a function that prints the file system structure in a hierarchical, lexicographically sorted format.

Input

  • paths: A list of strings, where each string represents a full path (e.g., "/home/user/docs/file.txt").

Output

  • Return a single string that visualizes the file system structure.
  • Directories should be listed before files within the same level.
  • Both directories and files must be sorted alphabetically at each level.
  • Use two spaces of indentation for each depth level.

Example

Input:

paths = [
    "/home/user/docs/notes.txt",
    "/home/user/docs/photos/",
    "/home/user/config",
    "/var/log"
]

Output:

home
  config
  user
    docs
      notes.txt
      photos
var
  log

Constraints

  • paths contains between 1 and 1000 strings.
  • Each path is a valid string separated by '/'.
  • Assume root directory is implied and paths start from the top level.

Edge Cases

  • Paths ending in '/' are directories; those without are files.
  • Handle deeply nested structures.
  • Ensure identical file names in different subdirectories are handled correctly.

Hints

Hint 1

Represent the file system using a nested dictionary or a Trie structure where each node stores its children.

Hint 2

Perform a depth-first traversal of your tree, sorting the keys at each node before recursing.

Hint 3

Keep a tracking variable or a boolean flag at each node to distinguish between files and directories to ensure proper formatting.

Follow-up questions

  • How would your approach change if you needed to output the file size alongside the name?
  • If the file system was extremely large and couldn't fit in memory, how would you optimize the storage structure?
  • What changes are needed to support a 'search' functionality that returns the path to a specific file given its name?