LeetCode 1598. Crawler Log Folder Java Problem Solution

HanHan
1 min read

Problem Description

  • Problem: LeetCode 1598

  • Description: Calculate the depth of the file system directory based on the given log array. "./" represents the current directory, and "../" represents the parent directory.

Approach

  • Idea: Traverse the given logs while tracking the directory depth.

  • Algorithm:

    1. Initialize the depth to 0.

    2. Traverse each log:

      • If the log is "./", skip it as it represents the current directory.

      • If the log is "../", decrease the depth by one if the current depth is greater than 0.

        • Ensure the depth doesn't go below 0 by checking if it is greater than 0 before decrementing.
      • For other cases, increase the depth as it represents moving into a new directory.

        • Use else if to check for logs that are neither "../" nor "./".
    3. After processing all logs, return the remaining depth.

Code

class Solution {
    public int minOperations(String[] logs) {
        int depth = 0;

        for (String log : logs) {
            if (log.equals("../")) {
                if (depth > 0) {
                    depth--;
                }
            } else if (!log.equals("./")) {
                depth++;
            }
        }

        return depth;
    }
}

Conclusion

  • Time Complexity: O(n) since we traverse the given log array once (where n is the length of the log array).

  • Space Complexity: O(1) as no additional space is used.

0
Subscribe to my newsletter

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

Written by

Han
Han