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 <stdio.h>
2#include <string.h>
3
4int minOperations(char **logs, int logsSize) {
5 int depth = 0;
6 for (int i = 0; i < logsSize; i++) {
7 if (strcmp(logs[i], "../") == 0) {
8 if (depth > 0) depth--;
9 } else if (strcmp(logs[i], "./") == 0) {
10 continue;
11 } else {
12 depth++;
13 }
14 }
15 return depth;
16}
17
18int main() {
19 char *logs[] = {"d1/", "d2/", "../", "d21/", "./"};
20 int logsSize = sizeof(logs) / sizeof(logs[0]);
21 printf("%d\n", minOperations(logs, logsSize));
22 return 0;
23}
The C implementation uses the strcmp
function to compare strings for directory operations and adjusts a counter representing the current directory depth. The final value of the counter gives the required number of operations to get back to the main folder.
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 Python function leverages a list as a stack to model navigation through folder structures, effectively performing operations mimicking push and pop actions.