Ctrl K

Longest Path to a File

Medium
A disk's contents are written as one string listing. Every folder or file is its own line, and lines are separated by \n. Each name is preceded by as many tab characters \t as its nesting depth: none for top-level items, one for the contents of such a folder, and so on. Each item belongs to the nearest folder above it in the list whose depth is one less. For example, "docs\n\tcv.pdf\n\told\n\t\tcv1.pdf" describes a folder docs holding the file cv.pdf and the folder old, which holds cv1.pdf. A name with a dot is a file and a name without one is a folder; files contain nothing. The full path of an item is the names of all folders from the top level down to it plus its own name, joined with /, such as docs/old/cv1.pdf. Return the length of the longest full path to a file. If there are no files, return 0.
Example 1
listing="notes\n\tdraft.md\n\tarchive\n\t\told.txt" → 21

There are two files: notes/draft.md (14 characters) and notes/archive/old.txt (21 characters).

Example 2
listing="music" → 0

There is only the folder music and no files.

Example 3
listing="a.b\nlong.name" → 9

Both files sit at the top level; the longer one, long.name, has 9 characters.

Constraints
  • 1 ≤ len(listing) ≤ 10⁴
  • listing consists of English letters, digits, spaces, dots, \n and \t
  • All names are non-empty and the structure is well formed
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsTree From Bracket Notation MediumTidy a Folder Route MediumWord Traced on a Letter Grid MediumTree Into a Right Chain MediumFour-Operation Calculator Medium
loading Python…
Input
listing="notes\n\tdraft.md\n\tarchive\n\t\told.txt"
Expected
21

Run checks the first 3 tests in your browser. Submit checks all 7 tests on the server, hidden ones included.