LeetCode #1598 Crawler Log Folder Solution & Explanation

LeetCode Problem

The Leetcode file system keeps a log each time some user performs a change folder operation.

The operations are described below:

  • “../” : Move to the parent folder of the current folder. (If you are already in the main folder, remain in the same folder).
  • “./” : Remain in the same folder.
  • “x/” : Move to the child folder named x (This folder is guaranteed to always exist).

You are given a list of strings logs where logs[i] is the operation performed by the user at the ith step.

The file system starts in the main folder, then the operations in logs are performed.

Return the minimum number of operations needed to go back to the main folder after the change folder operations.

Constraints:

Folder names consist of lowercase English letters and digits.

1 <= logs.length <= 103

2 <= logs[i].length <= 10

logs[i] contains lowercase English letters, digits, ‘.’, and ‘/’.

logs[i] follows the format described in the statement.


Solution

In this problem, we need a variable level to keep track of the current directory depth. Initially, level is set to 0, indicating that we are in the main directory. For each operation:

  • If the operation is “./”, it means staying in the current directory, so no changes are made to level.
  • If the operation is “../”, it means attempting to move up one directory. If we are already in the main directory (level is 0), level remains unchanged; otherwise, level is decreased by 1.
  • If the operation is “x/”, it means moving into a child directory, so level is increased by 1.

Finally, level represents the minimum number of operations needed to return to the main directory after performing all the operations.

C# Solution

Solution1

public class Solution {
    public int MinOperations(string[] logs) {
        int level = 0;
        foreach(var log in logs){
            if(log == "./"){
                continue;
            }
            else if(log == "../"){
                level -= level==0 ? 0 : 1; 
            }
            else{
                level+=1;
            }
        }

        return level;
    }
}

Java Solution

Solution1

class Solution {
    public int minOperations(String[] logs) {
        int level = 0;
        for(String log : logs){
            if(log.equals("./")){
                continue;
            }
            else if(log.equals("../")){
                level -= level==0 ? 0 : 1; 
            }
            else{
                level+=1;
            }
        }

        return level;
    }
}


Conclusion

🧡If my solution helps, that is my honor!

🧡You can support me by sharing my posts, thanks a lot

If you got any problem about the explanation, please feel free to let me know

The problem link : Crawler Log Folder – LeetCode

Some Random LeetCode posts

Leave a Reply

Your email address will not be published. Required fields are marked *