Crawler Log Folder (LeetCode)
Problem Link
Intuition
see whenever we write the commandcd /foldername
and suppose you are in the root directory so once this command is executed, how many steps you need to go back to root directory?
1 step right you will just peform cd ../
and you will go in home directory
so now can you tell me what will happen if you write the commandcd ./
?
we will stay in the same directory
So I can perform n
number of operations like this and then when I'm done playing with command line i can move back to root directory, by using cd ../
so still the minimum number of steps required to reach the root directory is - 1
maximum number of steps = n+1
for those who are not familiar with linuxcd
means change directory command../
represents previous directory/folder./
represents current directory/folder
Approach
We will be declaring a variable which will store the minimum number of operations required to get to the root directory.
We will be initializing this variable with
0
because initially we are already in the root directory, so the steps required to reach the root directory is0
Now we will iterate over the string and if the operation is
../
and the value ofoperation variable > 0
that means we are not in root directory, then we will decrease the value of our operation variable by 1 because we are moving backwards to the parent directory, so in a way we are reducing the number of operationsNow if the command is
./
that means we are not moving, neither backwards nor forward, and if we have commands other than this for example/abc
that means we are entering theabc
folder then, we will increase the value of operation variable by 1Return the value of Operation Variable
Complexity
Time complexity: O(n)
Space complexity: O(1)
Code
class Solution {
public:
int minOperations(vector<string>& logs) {
int operation = 0; // root directory condition
for(auto s:logs){
if(s=="../"){
if(operation >0){
operation --;
}
}
else if(s !="./"){
operation++;
}
}
return operation;
}
};
All the best for your DSA journey! Let me know your feedback so that we can improve this article together.
Ujjwal Sharma
Subscribe to my newsletter
Read articles from Ujjwal Sharma directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by