Longest Absolute File Path - Problem

Suppose we have a file system that stores both files and directories. Given a string input representing the file system in a specific format, return the length of the longest absolute path to a file in the abstracted file system.

The input string uses \n (newline) to separate different files/directories, and \t (tab) characters to represent the depth level in the directory hierarchy.

Each file name is of the form name.extension, while directory names consist of letters, digits, and/or spaces without extensions.

For example:

"dir\n\tsubdir1\n\t\tfile1.ext\n\t\tsubsubdir1\n\tsubdir2\n\t\tsubsubdir2\n\t\t\tfile2.ext"

represents the directory structure where file2.ext has the absolute path "dir/subdir2/subsubdir2/file2.ext" with length 32.

If there is no file in the system, return 0.

Input & Output

Example 1 — Basic Directory Structure
$ Input: 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. This beats "dir/subdir1/file1.ext" which has length 20.
Example 2 — Single File
$ Input: input = "file1.txt"
Output: 9
💡 Note: Only one file exists at root level with name "file1.txt", so the length is 9.
Example 3 — No Files
$ Input: input = "dir1\n\tdir2\n\t\tdir3"
Output: 0
💡 Note: All entries are directories (no extensions), so no files exist. Return 0.

Constraints

  • 1 ≤ input.length ≤ 104
  • input contains only valid directory/file names
  • File names contain exactly one '.' character
  • No empty directory or file names

Visualization

Tap to expand
File System to Absolute Path LengthsDirectory Structuredir subdir1 file1.ext subsubdir1 subdir2 subsubdir2 file2.extAbsolute Pathsdir/subdir1/file1.ext20dir/subdir2/subsubdir2/file2.ext32Find maximum length among all file pathsOutput: 32
Understanding the Visualization
1
Input
Parse directory structure with tab indentation
2
Process
Track path lengths using stack based on nesting depth
3
Output
Return length of longest absolute file path
Key Takeaway
🎯 Key Insight: Use a stack to track directory path lengths at each depth level - only calculate full paths when you encounter files
Asked in
Google 35 Amazon 28 Microsoft 22 Facebook 18
67.0K Views
Medium Frequency
~25 min Avg. Time
890 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