Sponsored
Sponsored
This approach involves maintaining a counter to keep track of the current folder depth. For each log operation, adjust the counter accordingly:
After processing all the logs, the counter will give the minimum operations needed to return to the main folder, as it represents the current depth.
Time Complexity: O(n), where n is the number of logs.
Space Complexity: O(1), no additional space is required except for the depth counter.
1def min_operations(logs):
2 depth = 0
3 for log in logs:
4 if log == "../":
5 if depth > 0:
6 depth -= 1
7 elif log == "./":
8 continue
9 else:
10 depth += 1
11 return depth
12
13logs = ["d1/", "d2/", "../", "d21/", "./"]
14print(min_operations(logs))
The Python code uses straightforward logic to iterate over log entries, adjusting depth based on each entry type. This results in a minimal and efficient solution.
This approach simulates navigating through folders using a stack. The stack keeps track of folder paths:
The stack's size at the end represents the current depth, which is the number of operations needed to return to the main folder.
Time Complexity: O(n).
Space Complexity: O(1).
1
The Java implementation utilizes a stack to replicate the current folder structure handling push and pop operations to navigate directories. Finally, it returns the stack's size.