Crawler Log Folder (LeetCode)

Ujjwal SharmaUjjwal Sharma
2 min read

Click Here

Intuition

see whenever we write the command
cd /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 command
cd ./?

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 linux
cd means change directory command
../ represents previous directory/folder
./ represents current directory/folder

Approach

  1. We will be declaring a variable which will store the minimum number of operations required to get to the root directory.

  2. 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 is 0

  3. Now we will iterate over the string and if the operation is ../ and the value of operation 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 operations

  4. Now 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 the abc folder then, we will increase the value of operation variable by 1

  5. Return 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

0
Subscribe to my newsletter

Read articles from Ujjwal Sharma directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Ujjwal Sharma
Ujjwal Sharma