Crawler Log Folder

Easy · Stack · Explanation and code example

Iteration

How it works

We do not actually need to store the folder names since we only care about the depth. A simple counter can track how many levels deep we are. Moving into a folder increments the counter, moving to parent decrements it (but never below 0 since we cannot go above the main folder), and "./" leaves it unchanged.

Steps

  1. Initialize a depth counter to 0.
  2. For each log operation:
    • If it is "./", skip (no change in depth).
    • If it is "../", decrement the counter but ensure it does not go below 0.
    • Otherwise, increment the counter (moving into a child folder).
  3. Return the counter value as the minimum operations to return to main folder.

Complexity

  • Time complexity: O(n)
  • Space complexity: O(1)

Things to watch for

Allowing Depth to Go Negative

When processing "../", you must ensure the depth does not go below zero. Going above the main folder is impossible, so decrementing when already at depth 0 produces wrong results.

Forgetting to Handle the Current Directory Operation

The operation "./" means stay in the current folder and should not change the depth. Treating it like a folder name and incrementing depth is a common mistake.

Python code example

from typing import List

class Solution:
    def minOperations(self, logs: List[str]) -> int:
        res = 0
        for log in logs:
            if log == "./":
                continue
            if log == "../":
                res = max(0, res - 1)
            else:
                res += 1
        return res

C++ code example

class Solution {
public:
    int minOperations(vector<string>& logs) {
        int res = 0;
        for (auto& log : logs) {
            if (log == "./") {
                continue;
            }
            if (log == "../") {
                res = max(0, res - 1);
            } else {
                res++;
            }
        }
        return res;
    }
};
Source and license

Adapted from NeetCode’s source · MIT license. Node types are supplied by LeetCode where needed.

Your recall check is in progress. Write your attempt before revealing the explanation.

Resume recall check

Browse all problem explanations