
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.
The Java solution uses a loop to traverse the log operations. The depth variable is adjusted based on the log type, keeping track of the current folder depth.
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).
1using System;
2using System.Collections.Generic;
3
4public class Solution {
5 public int MinOperations(string[] logs) {
6 Stack<string> stack = new Stack<string>();
7 foreach (string log in logs) {
8 if (log == "../") {
9 if (stack.Count > 0) stack.Pop();
10 } else if (log != "./") {
11 stack.Push(log);
12 }
13 }
14 return stack.Count;
15 }
16
17 public static void Main(string[] args) {
18 Solution solution = new Solution();
19 string[] logs = {"d1/", "d2/", "../", "d21/", "./"};
20 Console.WriteLine(solution.MinOperations(logs));
21 }
22}C# uses a Stack object to mimic folder paths, responding to directory operations by manipulating the stack's elements, with the final stack count giving the result.