algoadvance

Leetcode 1598. Crawler Log Folder

Problem Statement

The problem “1598. Crawler Log Folder” from LeetCode describes a folder system represented by a list of strings. Each string can be one of the following:

  1. "../" - Move up one level in the folder hierarchy.
  2. "./" - Remain in the current folder.
  3. "x/" - Move into the child folder named x.

You’re initially in the main folder and the task is to compute the minimum number of operations needed to reach the main folder after interpreting all operations given in the list.

Clarifying Questions

  1. Q: What should our output be?
    • A: The output should be an integer representing the minimum number of operations needed to be back at the main folder after evaluating all log operations.
  2. Q: Are there any constraints on the input size?
    • A: The length of the list (number of operations) can be up to 10^4, and each log entry will be a string of maximum length 3.
  3. Q: Are the operations valid (always possible to execute)?
    • A: Yes. For instance, there is no "../" operation at the main folder level which would result in an invalid operation.

Strategy

We can maintain a counter to keep track of the current folder level where:

After processing all commands, the resultant folder level will indicate how many levels deep or shallow we need to move to get back to the main folder, which simplifies to just the value of the level counter.

Code

#include <vector>
#include <string>

class Solution {
public:
    int minOperations(std::vector<std::string>& logs) {
        int level = 0;
        
        for (const auto& log : logs) {
            if (log == "../") {
                if (level > 0) {
                    level--;
                }
            } else if (log != "./") {
                level++;
            }
        }
        
        return level;
    }
};

Time Complexity

This solution efficiently processes each log entry exactly once and accumulates the operations needed to determine the final directory level.

Cut your prep time in half and DOMINATE your interview with AlgoAdvance AI