Longest Absolute File Path solution explained
Longest Absolute File Path gives you a folder tree written as text, one name per line with leading tabs showing the depth, and asks for the length of the longest full path to a file, where a file is a name containing a dot. Read the lines in order and keep, for each depth, the length of the path down to the current folder at that depth; a file's full length is its parent's path length plus its own name. One pass, O(n) time.
By Evin JohnPublished 7 min read
Restating the problem
A file system listing arrives as a single string. Each line holds one name. A line with no leading tab is at the top level; a line with k leading tabs is inside the nearest line above it that has k - 1 tabs. A name that contains a period is a file, anything else is a folder, and names may contain spaces. The absolute path of a file is the names from the top down to it, joined by single slashes. Return the length in characters of the longest such path to a file, or 0 if the listing has no files.
"proj\n\tsrc\n\t\tmain.py\n\tREADME.md"
proj
src
main.py proj/src/main.py (16)
README.md proj/README.md (14)
-> 16
"a.txt\nphotos\n\t2024\n\t\tbeach.jpeg"
a.txt a.txt (5)
photos
2024
beach.jpeg photos/2024/beach.jpeg (22)
-> 22
"notes\n\tdrafts" no files -> 0In the strings above, \n stands for a newline character and \t for a tab, as they would be written in source code. The input contains the real characters.
What it tests
This is a parsing problem whose structure is a tree walked in preorder. Interviewers want to see that you do not build the tree at all: because lines come in depth-first order, the current branch from the top to the line you are reading is all you ever need, and that branch behaves like a stack. They also check small details: counting tabs, telling files from folders, and the slashes in the length.
Slow but sure: rebuild every path
Keep the list of names on the current branch. For each line, cut the list back to the line's depth, append the name, and if it is a file, join the list with slashes and measure it. This is clear and correct, but each line copies and joins the whole branch, so the cost grows with depth times the number of lines.
def length_longest_path_slow(listing):
names, best = [], 0
for line in listing.split("\n"):
name = line.lstrip("\t")
depth = len(line) - len(name)
names = names[:depth] + [name]
if "." in name:
best = max(best, len("/".join(names)))
return bestOne pass with lengths per depth
You never need the names themselves, only lengths. Keep a list where entry d is the length of the path through all folders above depth d, including the slash after each. For a top-level line that is 0. When you read a folder at depth d, its children's prefix is the prefix at d plus the folder's name plus one slash, so store that at d + 1 and drop anything deeper, since that belonged to an earlier branch. When you read a file at depth d, its full path length is the prefix at d plus its name.
def length_longest_path(listing):
best = 0
prefix = [0] # prefix[d]: length of the folders above depth d, with slashes
for line in listing.split("\n"):
name = line.lstrip("\t")
depth = len(line) - len(name)
if "." in name:
best = max(best, prefix[depth] + len(name))
else:
del prefix[depth + 1:]
prefix.append(prefix[depth] + len(name) + 1)
return bestfunction lengthLongestPath(listing) {
const stack = []; // stack[d]: path length through the folder at depth d, plus "/"
let best = 0;
for (const line of listing.split("\n")) {
let depth = 0;
while (line[depth] === "\t") depth++;
const name = line.slice(depth);
while (stack.length > depth) stack.pop();
const base = stack.length ? stack[stack.length - 1] : 0;
if (name.includes(".")) best = Math.max(best, base + name.length);
else stack.push(base + name.length + 1);
}
return best;
}The two versions store the same numbers, shifted by one position. The file's length never includes a trailing slash, because the slash is only added when a folder becomes a prefix for something below it.
Tracing the second example
| Line | Depth | Stack after popping | Action | Stack / best after |
|---|---|---|---|---|
| a.txt | 0 | (empty) | file: 0 + 5 | best 5 |
| photos | 0 | (empty) | folder: push 0 + 6 + 1 | 7 |
| 2024 | 1 | 7 | folder: push 7 + 4 + 1 | 7, 12 |
| beach.jpeg | 2 | 7, 12 | file: 12 + 10 | best 22 |
Complexity
| Approach | Time | Extra space |
|---|---|---|
| Rebuild each full path | O(n · d) from copying and joining branches | O(d) names plus the joined string |
| Lengths per depth | O(n): each line handled once, each entry pushed and popped once | O(d) |
Inputs that catch bugs
- No files at all: return 0, even if the folders are long.
- A file at the top level, like "a.txt": its length is just its name.
- Names with spaces, like "my notes.txt": spaces are part of the name, not separators.
- A shallow line after a deep branch: the stack must shrink before it is read.
- A folder whose name has no dot but a file inside with a dot: only the file counts, even if a longer folder path exists elsewhere.
Common mistakes
- Returning the longest path to any name, folders included.
- Forgetting the slashes, or adding one after the file name.
- Splitting on spaces or on whitespace in general, which breaks names that contain spaces.
- Counting depth with a whitespace-trimming function that also removes leading spaces from the name.
- Not cutting the stack back before using it, so a file inherits the length of a branch it is not in.
Variations
- Return the path itself: store names alongside lengths and rebuild only the best path at the end.
- Depth marked by spaces: if each level is four spaces, divide the leading space count by four.
- Largest folder by total file size: lines carry sizes; add each file's size to every folder on the current stack.
- Canonical paths: when the input is one path with dots and double dots instead of a tree, use Simplify Path.
How to explain it out loud
Fictional example
- Candidate
- The lines come in depth-first order, so when I read a line, its parent is the most recent line with one fewer tab. I only need the current branch, not the whole tree.
- Candidate
- And I only need lengths. I keep the length of the path through each folder on the branch, including the slash after it, indexed by depth.
- Interviewer
- What happens when the depth goes back up?
- Candidate
- I cut the list back to the new depth first, because anything deeper belonged to a branch that just ended. Then a file adds its name to its parent's length, and a folder pushes its own length for its children.
Related problems
Simplify Path in this batch is the single-path cousin, and Score of Parentheses also keeps one running value per depth level. For trees given as real nodes rather than text, Binary Tree Level Order Traversal shows level-by-level processing.
Rehearsing with Natively
Text-parsing problems go wrong in the details, so it helps to hear yourself list them. Natively, on a Mac or Windows machine, can read the listing format from a screenshot in a practice run, suggest the lengths-per-depth approach, and transcribe your explanation so you can check whether you mentioned the tab count, the slashes and the no-files case before writing code. Natively as an interview assistant explains the rest.
Questions people ask
How do you solve Longest Absolute File Path?
Split the input into lines and count leading tabs for the depth. Keep the path length through each folder on the current branch, indexed by depth. For a folder, store parent length plus name plus one slash; for a file, compare parent length plus name with the best so far.
How do you tell a file from a folder?
In this problem a file name contains a period and a folder name does not.
What is the time complexity of Longest Absolute File Path?
O(n) for an input of n characters, with extra space proportional to the deepest level of nesting.
What should Longest Absolute File Path return with no files?
Zero. Paths to folders do not count, however long they are.
Where to go next
Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.
Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.
