MediumNo. 0388

Longest Absolute File Path — LeetCode 388 Python Solution

Pattern
Stack
Topics
Stack, Depth-First Search, String
Reading time
6 min

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

Example
dir
⟶ subdir1
⟶ ⟶ file1.ext
⟶ ⟶ subsubdir1
⟶ subdir2
⟶ ⟶ subsubdir2
⟶ ⟶ ⟶ file2.ext

Python solution

PythonSolution
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 ans

Complexity

Time
O(n)
Space · auxiliary
O(n)

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

Related problems
No.ProblemDifficulty
0385Mini ParserMedium
0394Decode StringMedium
0020Valid ParenthesesEasy
0071Simplify PathMedium
0094Binary Tree Inorder TraversalEasy
0114Flatten Binary Tree to Linked ListMedium

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.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity, invisible to screen sharing.

Free to download. Check it runs on your machine, then pick a plan.