Crawler Log Folder (LeetCode 1598): Solution and Explanation

Easy
Array
String
Stack

A list of folder changes starts in the main folder. "x/" enters a child, "../" goes up (but not above main) and "./" stays put. Return how many operations it takes to get back to main afterwards. For ["d1/","d2/","../","d21/","./"] the answer is 2.

Intuition

The natural model is a stack of open folders: entering a child pushes it, going up pops it. That works, but look at what the question asks for.

Getting home costs one "../" per folder on that stack, so only the stack's size matters, never the names in it.

That reduces the whole problem to one integer: the current depth below main, with a floor at zero.

Approach: Depth counter

  1. Set depth = 0 for the main folder.
  2. For each log: if it is "../", set depth = max(0, depth - 1).
  3. If it is "./", do nothing.
  4. Otherwise it names a child folder, so add one to depth.
  5. Return depth, the number of "../" operations needed to climb back.

Step-by-step example

logs = ["d1/","d2/","../","d21/","./"]
  1. d1/ enters d1. Depth 1.
  2. d2/ enters d2. Depth 2.
  3. ../ climbs back to d1. Depth 1.
  4. d21/ enters d21. Depth 2.
  5. ./ stays in d21. Depth 2.
  6. Two folders sit between the crawler and main, so the answer is 2.

Code: Python, Java, C++

1class Solution:
2    def minOperations(self, logs: List[str]) -> int:
3        depth = 0
4        for log in logs:
5            if log == "../":
6                depth = max(0, depth - 1)
7            elif log != "./":
8                depth += 1
9        return depth
Press play on the visualizer and the running line lights up here.

Time and space complexity

Time

O(n)

Each log is compared against two short constants once.

Space

O(1)

Only the depth counter is stored.

Other approaches

Explicit folder stack (time O(n), space O(n))

Push each child folder name, pop on "../" when the stack is not empty, and return the stack size. It gives the same answer and is useful if you also need the final path, but it uses O(n) space.

Common mistakes

  • Letting the depth go negative on a "../" in the main folder. Later child folders would then appear to bring you back to main.
  • Treating "./" as a child folder because it ends in a slash. Check for the two special logs first.
  • Comparing against ".." or "." without the trailing slash, which never matches the input.

Frequently asked questions

Why is the answer simply the final depth?

Each "../" climbs exactly one level, and you cannot skip levels, so the shortest way home from depth d is d operations.

Do folder names ever matter?

No. The problem guarantees every child folder exists, so a name only tells you that you went one level deeper.

How does this relate to Simplify Path?

Simplify Path uses the same rules on a Unix path but asks for the resulting path itself, so it needs the stack of names. Here only the stack size is needed.