Crawler Log Folder

Let’s break down the solution to the problem step-by-step:

  1. Start in the main folder, initialize a variable level to keep track of the current folder level (0 means the main folder).
  2. Iterate through the given logs:
    • If the log is “../”, move to the parent folder if you are not already in the main folder.
    • If the log is “./”, remain in the same folder.
    • Otherwise, move to the child folder, i.e., increase the level by 1.
  3. Return the level, which indicates the minimum number of operations needed to go back to the main folder.

Here’s the code:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
class Solution:
    def minOperations(self, logs: List[str]) -> int:
        level = 0  # Current folder level, starting at the main folder

        # Iterate through the logs
        for log in logs:
            if log == "../":  # Move to the parent folder if not in the main folder
                if level > 0:
                    level -= 1
            elif log == "./":  # Remain in the same folder
                continue
            else:  # Move to the child folder
                level += 1

        # Return the number of operations needed to go back to the main folder
        return level

The code follows the problem’s requirements, iterates through the logs, and modifies the current folder level based on the log’s content. The time complexity of this code is O(n), where n is the number of logs.