Longest Absolute File Path (LeetCode 388): Solution and Explanation
Given a file system written as lines with tab indentation, return the length of the longest absolute path to a file.
Intuition
The string is a tree printed depth first: every line is followed by its children, which have one more leading tab. So when a line at depth d appears, its parent is the latest folder seen at depth d - 1.
That means we only ever need the current chain of folders from the root down, which is exactly what a stack holds. Going deeper pushes; coming back up pops.
We do not need the names themselves, only how long the path is at each level. Storing lengths makes each file a single addition.
Approach: Stack of path lengths by depth
- Start with
stack = [0], the length before any folder. - Split the input on '\n'. For each line, strip the leading '\t' characters to get
name; the number stripped isdepth. - Pop until the stack has
depth + 1entries. Its top is now the length of the parent path including a trailing slash. - Compute
length = stack[-1] + len(name) + 1. - If
namecontains a dot, it is a file: updatebestwithlength - 1, since a file path has no trailing slash. Otherwise pushlengthfor this folder. - Return
best, which stays 0 if there is no file.
Step-by-step example
input = "dir\n\tsubdir1\n\tsubdir2\n\t\tfile.ext"
- "dir" at depth 0: length = 0 + 3 + 1 = 4. It is a folder, so the stack is [0, 4].
- "subdir1" at depth 1: the stack already has 2 entries. length = 4 + 7 + 1 = 12, push: [0, 4, 12].
- "subdir2" at depth 1: pop back to 2 entries, [0, 4]. length = 12, push: [0, 4, 12].
- "file.ext" at depth 2: length = 12 + 8 + 1 = 21. It is a file, so its path length is 20, the path "dir/subdir2/file.ext".
- best = 20.
Code: Python, Java, C++
1class Solution:
2 def lengthLongestPath(self, input: str) -> int:
3 stack = [0]
4 best = 0
5 for line in input.split('\n'):
6 name = line.lstrip('\t')
7 depth = len(line) - len(name)
8 while len(stack) > depth + 1:
9 stack.pop()
10 length = stack[-1] + len(name) + 1
11 if '.' in name:
12 best = max(best, length - 1)
13 else:
14 stack.append(length)
15 return best1class Solution {
2 public int lengthLongestPath(String input) {
3 Deque<Integer> stack = new ArrayDeque<>();
4 stack.push(0);
5 int best = 0;
6 for (String line : input.split("\n")) {
7 String name = line.replaceAll("^\t+", "");
8 int depth = line.length() - name.length();
9 while (stack.size() > depth + 1) {
10 stack.pop();
11 }
12 int length = stack.peek() + name.length() + 1;
13 if (name.contains(".")) {
14 best = Math.max(best, length - 1);
15 } else {
16 stack.push(length);
17 }
18 }
19 return best;
20 }
21}1class Solution {
2public:
3 int lengthLongestPath(string input) {
4 vector<int> stack = {0};
5 int best = 0;
6 stringstream ss(input);
7 string line;
8 while (getline(ss, line, '\n')) {
9 int depth = 0;
10 while (depth < (int)line.size() && line[depth] == '\t') depth++;
11 string name = line.substr(depth);
12 while ((int)stack.size() > depth + 1) {
13 stack.pop_back();
14 }
15 int length = stack.back() + (int)name.size() + 1;
16 if (name.find('.') != string::npos) {
17 best = max(best, length - 1);
18 } else {
19 stack.push_back(length);
20 }
21 }
22 return best;
23 }
24};Time and space complexity
O(n)
Each character is read a constant number of times while splitting and stripping, and each folder is pushed and popped once.
O(n)
The split lines take O(n); the stack itself holds at most one entry per depth level.
Other approaches
Array indexed by depth (time O(n), space O(d))
Instead of popping, keep lengths[depth + 1] = lengths[depth] + len(name) + 1 in an array and simply overwrite it. Deeper stale entries are never read because a line only looks at its own parent level.
Build the tree, then DFS (time O(n), space O(n))
Parse the lines into explicit folder and file nodes, then walk the tree carrying the path length. It works but stores every name and is more code than the single pass.
Common mistakes
- Counting the trailing slash for files. A folder adds its name plus '/', but a file path ends at the extension, so subtract 1.
- Treating spaces as indentation. Only '\t' sets the depth; leading spaces are part of the name.
- Deciding file versus folder by position. A file is any name containing a dot, and a folder can be a leaf with no children.
- In languages where the string arrives escaped, make sure '\n' and '\t' are real characters before splitting.
Frequently asked questions
Why does popping to depth + 1 entries give the parent?
stack[i] is the path length down to the folder at depth i - 1. A line at depth d needs its parent at depth d - 1, which is stack[d]. Any entries above that belong to folders the scan has already left.
What if there is no file at all?
best never changes from its starting value, so the answer is 0, as in the input "a".
Can a folder name contain a dot?
No. The problem guarantees that only file names contain a dot, which is why checking for '.' is enough.
Does the order of siblings matter?
No. Every file is measured when it is read, and best keeps the maximum, so sibling order only changes which frames show a new best.