Medium

Quiz

#388 Longest Absolute File Path

APPROACH

A file system is serialized into a single string input. Each line represents one entry; leading tab characters ('\t') encode nesting depth — one tab per level. Entries whose name contains a dot are files; all others are directories.

The absolute path to an entry is formed by joining its ancestor directory names and its own name with '/'.

Return the number of characters in the longest absolute path that terminates at a file. Return 0 when no file is present in the input. Every entry name is guaranteed non-empty.

Example 1:

dir
⟶ subdir1
⟶ ⟶ file1.ext
⟶ ⟶ subsubdir1
⟶ subdir2
⟶ ⟶ subsubdir2
⟶ ⟶ ⟶ file2.ext

Example 2:

Input: input = "dir\n\tsubdir1\n\tsubdir2\n\t\tfile.ext"
Output: 20
Explanation: We have only one file, and the absolute path is "dir/subdir2/file.ext" of length 20.

Example 3:

Input: input = "dir\n\tsubdir1\n\t\tfile1.ext\n\t\tsubsubdir1\n\tsubdir2\n\t\tsubsubdir2\n\t\t\tfile2.ext"
Output: 32
Explanation: We have two files:
"dir/subdir1/file1.ext" of length 21
"dir/subdir2/subsubdir2/file2.ext" of length 32.
We return 32 since it is the longest absolute path to a file.

Example 4:

Input: input = "a"
Output: 0
Explanation: We do not have any files, just a single directory named "a".
1 of 4
1:00

What is the optimal approach for this problem?