A folder tree is written as text, one entry per line. Lines are separated by \n, and the number of tab characters \t in front of a name says how deep it sits: a line with k tabs lives inside the closest line above it that has k − 1 tabs. A name with a dot, like notes.txt, is a file; any other name is a folder.
The full path of a file joins the names from the top folder down to it with /, for example proj/src/app.js. Return the length of the longest full path that ends in a file. If the tree holds no file, return 0.
Example 1
Input: input = "proj\n\tsrc\n\t\tapp.js\n\tdocs\n\t\tguide\n\t\t\tintro.md" Output: 24 Why: proj/docs/guide/intro.md has 24 characters; proj/src/app.js has 15
2 more examples and the constraints
Example 2
Input: input = "music" Output: 0 Why: one folder and no file
Example 3
Input: input = "readme.txt" Output: 10 Why: a file at the top level; its path is just its name
Constraints
- 1 ≤ length of input ≤ 10,000
- input holds letters, digits, spaces, dots,
\nand\t - Every name has at least one character, and the tree is well formed
Your turn first
Have a go on paper or in your own editor, then reveal the approaches from the simplest up.
- Keep the folder namesO(n·d)
- Stack of path lengthsO(n)
The idea in one sentence
The pattern, how to spot it, and the best complexity.
Side by side
| Approach | Time | Relative work for a 10,000-character input | Verdict |
|---|---|---|---|
| Keep the folder names | O(n·d) | Passes; rebuilds each path | |
| Stack of path lengths | O(n) | Best; one addition per line |
n = length of the input, d = deepest level of the tree.
Edge cases to test
- No file at all. "music" gives 0, not the length of the folder.
- A file at the top. "readme.txt" gives 10; there is no slash in front of it.
- Several top-level entries. Lines with no tabs can appear more than once; each starts a new tree.
- Climbing up several levels. A line can drop from depth 3 to depth 1, so pop more than once.
- Spaces in names. "my docs\n\tfile one.txt" gives 20. Spaces count as characters, and only tabs mean depth.
Common mistakes
- Counting the length of a folder path as the answer when the tree has no file.
- Adding the slash after the file name too, so every answer is one too long.
- Treating spaces like tabs, or treating every dot-free name as a file.
How to talk through it
- 1Clarify. Is a dot always a file? Can there be several top-level folders? What if there is no file?
- 2Parse the depth. Split on newlines and count leading tabs; that number is the depth.
- 3Keep the current path. Cut the path back to the depth on each line, then extend it. Joining names works but repeats work.
- 4Switch to lengths. Store each open folder's path length with its slash, so a file costs one addition.
- 5Test out loud. Run no file, a top-level file, and a jump back up two levels.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?