1598. Crawler Log Folder
EasyView on LeetCode
Time: O(n)
Space: O(1)
Advertisement
Intuition
Count operations on a file system. Only valid operations increment the counter: mkdir creates a new folder, rmdir removes empty folder. Others (cd, ls) don't count.
Algorithm
- 1For each log entry: increment count. But "cd .." and "ls" don't count, nor does "cd x" if x exists in current directory.
- 2Wait: problem counts minimum operations to return to main folder from cd operations. Use depth tracking.
Common Pitfalls
- •Each "cd x" where x!=".." increases depth by 1. "../" decreases by 1 (floor 0). "./" stays. Return final depth.
1598.cs
C#
// Approach: Simulate directory depth: '../' decrements, './' stays, otherwise increment; clamp at 0.
// Time: O(n) Space: O(1)
public class Solution
{
public int MinOperations(string[] logs)
{
int ops = 0;
foreach (string log in logs)
{
if (log == "./")
continue;
if (log == "../")
{
if (ops > 0)
ops--;
}
else
ops++;
}
return ops;
}
}Advertisement
Was this solution helpful?