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.
1using System;
2
3public class Solution {
4 public int MinOperations(string[] logs) {
5 int depth = 0;
6 foreach (string log in logs) {
7 if (log == "../") {
8 if (depth > 0) depth--;
9 } else if (log != "./") {
10 depth++;
11 }
12 }
13 return depth;
14 }
15
16 public static void Main(string[] args) {
17 Solution solution = new Solution();
18 string[] logs = {"d1/", "d2/", "../", "d21/", "./"};
19 Console.WriteLine(solution.MinOperations(logs));
20 }
21}
The C# implementation adjusts an integer depth counter as it iterates over the log operations. The depth counter efficiently tracks the current directory level.
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#include <string>
#include <iostream>
using namespace std;
int minOperations(vector<string>& logs) {
vector<string> stack;
for (const auto& log : logs) {
if (log == "../") {
if (!stack.empty()) stack.pop_back();
} else if (log != "./") {
stack.push_back(log);
}
}
return stack.size();
}
int main() {
vector<string> logs = {"d1/", "d2/", "../", "d21/", "./"};
cout << minOperations(logs) << endl;
return 0;
}
The C++ solution employs a vector to simulate a stack, using push and pop operations to track directories. The vector's size aids in computing the minimal operation count.