Crawler Log Folder - Problem

The Leetcode file system keeps a log each time some user performs a change folder operation.

The operations are described below:

  • "../": Move to the parent folder of the current folder. (If you are already in the main folder, remain in the same folder).
  • "./": Remain in the same folder.
  • "x/": Move to the child folder named x (This folder is guaranteed to always exist).

You are given a list of strings logs where logs[i] is the operation performed by the user at the ith step.

The file system starts in the main folder, then the operations in logs are performed.

Return the minimum number of operations needed to go back to the main folder after the change folder operations.

Input & Output

Example 1 — Basic Navigation
$ Input: logs = ["d1/","d2/","../","d21/","./"]
Output: 2
💡 Note: Start at main → d1 (depth 1) → d2 (depth 2) → back to d1 (depth 1) → d21 (depth 2) → stay in d21 (depth 2). Need 2 operations to return to main.
Example 2 — Stay at Main
$ Input: logs = ["d1/","../","../","../"]
Output: 0
💡 Note: Start at main → d1 (depth 1) → back to main (depth 0) → try to go up but stay at main (depth 0) → stay at main (depth 0). Already at main, need 0 operations.
Example 3 — Only Stay Operations
$ Input: logs = ["./","./","./"]
Output: 0
💡 Note: All operations are stay commands, remain at main folder throughout. Need 0 operations to return.

Constraints

  • 1 ≤ logs.length ≤ 103
  • 2 ≤ logs[i].length ≤ 10
  • logs[i] contains lowercase English letters, digits, '.', and '/'
  • logs[i] follows the format described in the statement

Visualization

Tap to expand
Crawler Log Folder - Counter Approach INPUT File System Navigation main/ d1/ d2/ d21/ logs[] Array: d1/ d2/ ../ d21/ ./ [0] [1] [2] [3] [4] x/ = go deeper | ../ = go up | ./ = stay depth = 0 (start at main) ALGORITHM STEPS 1 Initialize depth = 0 Start at main folder 2 Loop through logs Process each operation 3 Update counter Based on operation type 4 Return depth Final depth = answer Execution Trace: Operation Action Depth d1/ +1 0 --> 1 d2/ +1 1 --> 2 ../ -1 2 --> 1 d21/ +1 1 --> 2 ./ 0 2 --> 2 Final depth = 2 FINAL RESULT Current Position After All Operations: main/ depth = 0 d1/ depth = 1 d21/ depth = 2 (HERE) YOU Output: 2 OK - Need 2 operations to return to main folder (../ then ../) Key Insight: The depth counter tracks how deep we are in the folder hierarchy. For "x/", increment depth. For "../", decrement depth (but never below 0). For "./", do nothing. Final depth = min operations to return. Time: O(n) | Space: O(1) - Only need one counter variable! TutorialsPoint - Crawler Log Folder | Counter Approach
Asked in
Amazon 15 Microsoft 8
34.0K Views
Medium Frequency
~10 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen