Longest Absolute File Path

Twice the number of downvotes. Be quick to learn.

The problem is to find the length of the longest absolute path to a file in the given file system. We can solve this problem by simulating the file system’s hierarchy using a stack and keeping track of the current path’s length.

Here’s the code for the solution:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
class Solution:
    def lengthLongestPath(self, input: str) -> int:
        stack = [] # To keep track of the length of the path at each depth
        max_length = 0 # To store the length of the longest absolute path to a file
        
        # Split the input by '\n' to iterate through files and directories
        for line in input.split('\n'):
            # Count the number of tabs to find the depth
            depth = line.count('\t')
            # Remove the tabs to get the name
            name = line[depth:]
            
            # If the stack is deeper than the current depth, pop elements from the stack
            while len(stack) > depth:
                stack.pop()
            
            # If the stack is empty, the current length is the length of the name
            # Otherwise, it is the length at the previous depth plus the length of the name plus 1 (for the '/')
            current_length = len(name) if not stack else stack[-1] + len(name) + 1
            stack.append(current_length)
            
            # If the name represents a file (contains '.'), update the max_length
            if '.' in name:
                max_length = max(max_length, current_length)
        
        return max_length

Explanation:

  • We split the input by ‘\n’ and iterate through files and directories.
  • We use the stack to keep track of the current length at each depth.
  • We update the stack based on the depth and whether the name represents a file or directory.
  • We return the length of the longest absolute path to a file.

This solution processes each file and directory name in the input and efficiently keeps track of the current path’s length using a stack, satisfying the given constraints and requirements.