Crawler Log Folder - Problem
Imagine you're navigating through a file system using terminal commands! ๐ฅ๏ธ
A web crawler keeps a detailed log every time it changes directories. You start in the main folder (root directory), and the crawler performs a series of folder operations based on these commands:
"../"- Move to the parent folder (go back one level). If you're already in the main folder, you stay put!"./"- Stay in the current folder (do nothing)"x/"- Move into a child folder named "x" (go deeper into the directory tree)
Given an array logs where each element represents a folder operation, determine the minimum number of steps needed to return to the main folder after all operations are complete.
Think of it like counting how many "cd ../" commands you need to get back to the root directory!
Input & Output
example_1.py โ Basic Navigation
$
Input:
logs = ["d1/", "d2/", "../", "d21/", "./"]
โบ
Output:
2
๐ก Note:
Starting from main folder: d1/ (depth=1) โ d2/ (depth=2) โ ../ (depth=1) โ d21/ (depth=2) โ ./ (depth=2). Need 2 operations to return to main folder.
example_2.py โ Stay in Main Folder
$
Input:
logs = ["d1/", "../", "../", "../"]
โบ
Output:
0
๐ก Note:
Starting from main: d1/ (depth=1) โ ../ (depth=0) โ ../ (depth=0, can't go higher) โ ../ (depth=0). Already in main folder.
example_3.py โ Only Current Directory
$
Input:
logs = ["./", "./", "./"]
โบ
Output:
0
๐ก Note:
All operations keep us in the current folder (main folder). No movement occurs, so 0 operations needed to return.
Visualization
Tap to expand
Understanding the Visualization
1
Start at Main Folder
Initialize depth counter to 0, representing the main/root folder
2
Navigate Through Operations
For each folder operation: increment for child folders, decrement for parent folders, ignore current folder
3
Count Steps Home
The final depth value tells us how many '../' operations we need to return to main
Key Takeaway
๐ฏ Key Insight: We only need to track our current depth from the main folder, not the actual folder names or complete path!
Time & Space Complexity
Time Complexity
O(n)
Single pass through all n operations with O(1) work per operation
โ Linear Growth
Space Complexity
O(1)
Only uses a single integer variable regardless of input size
โ Linear Space
Constraints
- 1 โค logs.length โค 103
- 2 โค logs[i].length โค 10
- logs[i] contains lowercase English letters, digits, '.', and '/'
- logs[i] is guaranteed to be a valid folder operation
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code