Leetcode Problem 388: Longest Absolute File Path
Suppose we have a file system represented in the following string format:
The string "dir\n\tsubdir1\n\tsubdir2\n\t\tfile.ext"
represents:
dir
subdir1
subdir2
file.ext
The directory dir
contains an empty subdirectory subdir1
and a subdirectory subdir2
containing a file file.ext
.
We need to find the length of the longest absolute path to a file within our file system.
Note:
.
and an extension.\n
, \t
, and it will not be empty."dir"
/"subdir2"
is a valid input.\t
.\n
for new lines and \t
for indentation levels..ext
, or any file with a .
in its name?
.
in its name.0
.\n
to process each line separately.\t
..
), update the maximum length if the current path length is greater.def lengthLongestPath(input: str) -> int:
# Split the input by newline to get each component in the hierarchy
lines = input.split('\n')
# Dictionary to store current path length at each depth
path_length = {0: 0}
max_length = 0
for line in lines:
# Count the depth by number of leading '\t'
depth = line.count('\t')
# Strip the leading '\t' characters to get the name of the directory or file
name = line.lstrip('\t')
# If it's a file, check and update max_length
if '.' in name:
max_length = max(max_length, path_length[depth] + len(name))
else:
# If it's a directory, update the path length for the next level
path_length[depth + 1] = path_length[depth] + len(name) + 1
return max_length
This solution efficiently traverses the hierarchical structure represented in the input string and calculates the longest absolute file path, considering memory and computational constraints.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?