Problem Description
Design a file system that supports creating new paths associated with specific integer values and retrieving the value of a given path. Each path is a string that starts with "/" and contains one or more lowercase English letters for each folder. The creation of a new path fails if the path already exists or if its immediate parent does not exist.
Key Insights
- Use a data structure (like a hash map) to store paths and associated values.
- To create a new path, check that the path does not already exist.
- Ensure the immediate parent path exists before creation.
- When retrieving a value, simply look it up in the storage structure.
- Splitting the path by "/" allows easy identification of the parent.
Space and Time Complexity
Time Complexity:
- createPath: O(n) per call where n is the number of segments in the path (to process and validate parent path).
- get: O(1) per call if using a hash map. Space Complexity: O(m * L) where m is the number of paths stored and L is the average length of a path.
Solution
The solution uses a hash map (dictionary) to store file paths along with their associated values. For the createPath method, the algorithm:
- Checks if the path already exists.
- Extracts the parent path by removing the last segment.
- Validates the existence of the parent path.
- Inserts the new path with its corresponding value if validation passes. For the get method, the algorithm simply returns the stored value if the path exists; otherwise, it returns -1. This approach ensures efficient lookup and validation using string manipulation and hash map operations.