Longest Absolute File Path - Problem
Imagine you're exploring a complex file system structure represented as a text string! ๐
You're given a string representation of a file system where:
- Directories and files are separated by newline characters (
\n) - Depth/nesting level is indicated by the number of tab characters (
\t) - Files contain a dot (.) in their name (like
file.txt) - Directories do not contain dots
Example: The string "dir\n\tsubdir1\n\t\tfile1.ext\n\tsubdir2\n\t\tsubsubdir2\n\t\t\tfile2.ext" represents:
dir subdir1 file1.ext subdir2 subsubdir2 file2.ext
Your mission: Find the length of the longest absolute path to any file in this system. An absolute path includes all directory names separated by forward slashes, like "dir/subdir2/subsubdir2/file2.ext".
If there are no files in the system, return 0.
Input & Output
example_1.py โ Basic Directory Structure
$
Input:
"dir\n\tsubdir1\n\t\tfile1.ext\n\t\tsubsubdir1\n\tsubdir2\n\t\tsubsubdir2\n\t\t\tfile2.ext"
โบ
Output:
32
๐ก Note:
The longest path is "dir/subdir2/subsubdir2/file2.ext" with length 32. We have: 'dir' (3) + '/' (1) + 'subdir2' (7) + '/' (1) + 'subsubdir2' (10) + '/' (1) + 'file2.ext' (9) = 32 characters total.
example_2.py โ Single File
$
Input:
"file1.txt"
โบ
Output:
9
๐ก Note:
There's only one file 'file1.txt' at the root level, so the longest path length is simply 9 (the length of 'file1.txt').
example_3.py โ No Files
$
Input:
"dir\n\tsubdir1\n\tsubdir2"
โบ
Output:
0
๐ก Note:
There are only directories in the system, no files. Since we need to find the longest path to a file, and there are no files, we return 0.
Constraints
- 1 โค input.length โค 104
- input contains only valid English letters, digits, spaces, '\n', and '\t'
- All folder and file names have length in range [1, 10]
- The depth of the folder structure will not exceed 1000
- File names contain exactly one dot to separate name and extension
Visualization
Tap to expand
Understanding the Visualization
1
Stack Initialization
Start with stack [0] representing root level with path length 0
2
Depth Detection
Count tabs in each line to determine directory depth level
3
Stack Management
Adjust stack size to match current depth, maintaining parent path lengths
4
Path Length Calculation
Add current name length to parent's path length plus separator
5
File Processing
When encountering a file (contains '.'), update maximum path length
Key Takeaway
๐ฏ Key Insight: The stack maintains cumulative path lengths at each depth, allowing us to calculate any file's absolute path length in constant time as we encounter it, achieving optimal O(n) time complexity.
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code