Leetcode 1598. Crawler Log Folder
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:
"../"
- Move up one level in the folder hierarchy."./"
- Remain in the current folder."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.
"../"
operation at the main folder level which would result in an invalid operation.We can maintain a counter to keep track of the current folder level where:
level = 0
corresponds to the main folder.x/
increases the level by 1."../"
decreases the level by 1 or remains the same if already at the main folder."./"
does not change the level.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.
#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;
}
};
n
is the number of operations in the logs
array. Each operation is processed in constant time.level
).This solution efficiently processes each log entry exactly once and accumulates the operations needed to determine the final directory level.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?