We use cookies (including Google cookies) to personalize ads and analyze traffic. By continuing to use our site, you accept our Privacy Policy.

Crawler Log Folder

Number: 1720

Difficulty: Easy

Paid? No

Companies: Amazon, Flipkart, Atlassian, Meta, Mercari


Problem Description

Given a list of log operations representing directory changes in a file system, determine how many steps are needed to return to the main folder. The operations include:

  • "x/": Move to a child directory named x.
  • "../": Move up to the parent directory (if not already at the main folder).
  • "./": Remain in the same directory.

The goal is to simulate the operations and return the current depth, which indicates how many "../" operations are required to return to the main folder.


Key Insights

  • The problem can be approached by simulating the file system operations using a counter or stack.
  • Increment the counter for moving into a subdirectory.
  • Decrement the counter for moving to the parent directory (ensuring it doesn’t go below zero).
  • Ignore operations that do not change the directory (like "./").

Space and Time Complexity

Time Complexity: O(n) - Each log is processed once. Space Complexity: O(1) - Only a counter is used (or O(n) if using a stack, but unnecessary for this problem).


Solution

We use a counter to track the current directory depth. For each log, we check:

  1. If the operation is "../" and the counter is greater than 0, we decrement the counter.
  2. If the operation is "./", we do nothing.
  3. Otherwise, we increment the counter as we enter a subdirectory. At the end of the simulation, the counter value equals the minimum number of "../" operations needed to return to the main folder.

Code Solutions

# Python solution with clear variable names and line-by-line comments
def minOperations(logs):
    # Initialize the current depth to 0 (main folder)
    current_depth = 0
    # Process each operation in the logs list
    for log in logs:
        if log == "../":
            # If not at the main folder, move up one level
            if current_depth > 0:
                current_depth -= 1
        elif log == "./":
            # Stay in the same folder, no changes needed
            continue
        else:
            # Move to the child folder, increment the depth
            current_depth += 1
    return current_depth

# Example usage:
logs = ["d1/", "d2/", "../", "d21/", "./"]
print(minOperations(logs))  # Expected output: 2
← Back to All Questions