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.
1#include <vector>
2#include <string>
3#include <iostream>
4
5using namespace std;
6
7int minOperations(vector<string>& logs) {
8 int depth = 0;
9 for (const string& log : logs) {
10 if (log == "../") {
11 if (depth > 0) depth--;
12 } else if (log == "./") {
13 continue;
14 } else {
15 depth++;
16 }
17 }
18 return depth;
19}
20
21int main() {
22 vector<string> logs = {"d1/", "d2/", "../", "d21/", "./"};
23 cout << minOperations(logs) << endl;
24 return 0;
25}
The C++ solution iterates through the logs, modifying a depth counter based on each log's operation. This depth counter directly indicates how many operations are needed to return to the root.
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 C solution mimics the behavior of a stack using an integer counter to track how many directories down the user is. It simulates pushing and popping with integer operations.