#1598
Crawler Log Folder
EasyArrayStringStackStackArray
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(1) |
💡
Intuition
Time O(n)Space O(1)
The optimal solution also tracks the depth of the current folder but does so in a single pass through the logs. This approach is efficient and straightforward, ensuring we only count the necessary operations to return to the main folder.
⚙️
Algorithm
4 steps- 1Step 1: Initialize a variable to track the current depth, starting at 0.
- 2Step 2: Loop through each log entry in the logs.
- 3Step 3: For each log, adjust the depth: decrease for '../', increase for 'x/', and ignore './'.
- 4Step 4: After processing all logs, the depth variable will directly represent the number of operations needed to return to the main folder.
solution.py8 lines
1def minOperations(logs):
2 depth = 0
3 for log in logs:
4 if log == '../':
5 depth = max(0, depth - 1)
6 elif log != './':
7 depth += 1
8 return depthℹ
Complexity note: The time complexity is O(n) since we only make a single pass through the logs. The space complexity is O(1) because we only use a single integer to track the depth.
- 1Each '../' operation decreases depth, while each 'x/' increases it.
- 2The './' operation does not affect the depth.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.