Longest Absolute File Path — LeetCode 388 Python Solution
- Problem
- #388
- Pattern
- Stack
- Reading time
- 6 min
- Source
- leetcode.com
The problem
Suppose we have a file system that stores both files and directories. An example of one system is represented in the following picture: Here, we have dir as the only directory in the root.
Example
dir ⟶ subdir1 ⟶ ⟶ file1.ext ⟶ ⟶ subsubdir1 ⟶ subdir2 ⟶ ⟶ subsubdir2 ⟶ ⟶ ⟶ file2.ext
Python solution
class Solution:
def lengthLongestPath(self, input: str) -> int:
i, n = 0, len(input)
ans = 0
stk = []
while i < n:
ident = 0
while input[i] == '\t':
ident += 1
i += 1
cur, isFile = 0, False
while i < n and input[i] != '\n':
cur += 1
if input[i] == '.':
isFile = True
i += 1
i += 1
# popd
while len(stk) > 0 and len(stk) > ident:
stk.pop()
if len(stk) > 0:
cur += stk[-1] + 1
# pushd
if not isFile:
stk.append(cur)
continue
ans = max(ans, cur)
return ansComplexity
| Measure | Complexity |
|---|---|
| Time | O(n) |
| Space | O(n) auxiliary |
Pattern: Stack
When the most recent unresolved thing is the one that matters, use a stack. LeetCode 388. Longest Absolute File Path is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Stack.
The stack guide has the Python template for the pattern and the 194 LeetCode problems that use it.
Related problems
Frequently asked questions
- How hard is LeetCode 388. Longest Absolute File Path?
- LeetCode 388. Longest Absolute File Path is rated Medium on LeetCode.
- What is the time complexity of LeetCode 388. Longest Absolute File Path?
- The Python solution on this page runs in O(n).
- What is the space complexity of LeetCode 388. Longest Absolute File Path?
- The Python solution on this page uses O(n) auxiliary space.
- What topics does LeetCode 388. Longest Absolute File Path cover?
- LeetCode 388. Longest Absolute File Path is tagged Stack, Depth-First Search and String on LeetCode.