323. Longest Absolute File Path
A whole file system has been flattened into one string fs. Entries are separated by newline characters (\n), and an entry that sits k levels below the root is prefixed by exactly k tab characters (\t). An entry whose name contains a period . is a file; every other entry is a directory. Entries appear in depth-first order, so each entry's parent is the closest earlier entry that is one level shallower.
Return the length, in characters, of the longest absolute path to a file, where an absolute path joins every name from the root down with / separators — for example dir/subdir2/file.ext. If fs contains no file at all, return 0.
The tabs and newlines are pure structure: they never count toward a path's length, but every / separator does.
Example 1:
Input: fs = "dir\n\tsubdir1\n\tsubdir2\n\t\tfile.ext"
Output: 20
Explanation: The tree is dir with children subdir1 and subdir2, and file.ext inside subdir2. The only file path is "dir/subdir2/file.ext", which is 20 characters long.
Example 2:
Input: fs = "dir\n\tsubdir1\n\t\tfile1.ext\n\t\tsubsubdir1\n\tsubdir2\n\t\tsubsubdir2\n\t\t\tfile2.ext"
Output: 32
Explanation: Two files exist: "dir/subdir1/file1.ext" (21 characters) and "dir/subdir2/subsubdir2/file2.ext" (32 characters). The longer one wins.
Constraints:
- 1 ≤ fs.length ≤ 10⁴
- Entry names consist of English letters, digits, and periods.
- A name containing a period is always a file; directory names never contain periods.
- The input is a valid tree: an entry at depth k+1 is always preceded by an ancestor chain down to depth k.
Hints:
Split on newlines and count each line's leading tabs: that gives you a list of (depth, name) pairs in depth-first order.
Because entries arrive depth-first, when you reach an entry at depth d, its parent is simply the most recent entry seen at depth d − 1. Keep a running path length per depth — plen[d + 1] = plen[d] + len(name) + 1 for a directory — and try plen[d] + len(name) as an answer whenever the name is a file.
▶ Run checks these sample cases. Submit also runs hidden edge cases.
Input: fs = "dir\n\tsubdir1\n\tsubdir2\n\t\tfile.ext"
Expected output: 20