Longest Absolute File Path (LeetCode 388): Solution and Explanation

Medium
String
Stack
Depth First Search

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

  1. Start with stack = [0], the length before any folder.
  2. Split the input on '\n'. For each line, strip the leading '\t' characters to get name; the number stripped is depth.
  3. Pop until the stack has depth + 1 entries. Its top is now the length of the parent path including a trailing slash.
  4. Compute length = stack[-1] + len(name) + 1.
  5. If name contains a dot, it is a file: update best with length - 1, since a file path has no trailing slash. Otherwise push length for this folder.
  6. Return best, which stays 0 if there is no file.

Step-by-step example

input = "dir\n\tsubdir1\n\tsubdir2\n\t\tfile.ext"
  1. "dir" at depth 0: length = 0 + 3 + 1 = 4. It is a folder, so the stack is [0, 4].
  2. "subdir1" at depth 1: the stack already has 2 entries. length = 4 + 7 + 1 = 12, push: [0, 4, 12].
  3. "subdir2" at depth 1: pop back to 2 entries, [0, 4]. length = 12, push: [0, 4, 12].
  4. "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".
  5. 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 best
Press play on the visualizer and the running line lights up here.

Time and space complexity

Time

O(n)

Each character is read a constant number of times while splitting and stripping, and each folder is pushed and popped once.

Space

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.