Crawler Log Folder Solution in C++

Problem Description

Welcome to the world of Crawler Log Folders, where navigating through directories is as easy as finding your way through a maze blindfolded! Imagine you’re a digital explorer, trying to find your way through a labyrinth of folders, but instead of a map, you have a series of logs that tell you where to go.

The problem is simple: you have a list of logs that represent your navigation commands. Each log can either tell you to stay put (./), go back one directory (../), or enter a new directory (any other string). Your mission, should you choose to accept it, is to determine how many directories you end up in after processing all the logs.

Think of it like trying to find your way out of a messy closet after your mom told you to clean it up. You might end up backtracking a lot, but at the end of the day, you just want to know how many new outfits you found!

Code Solution


class Solution {
 public:
  int minOperations(vector& logs) {
    int ans = 0;

    for (const string& log : logs) {
      if (log == "./")
        continue;
      if (log == "../")
        ans = max(0, ans - 1);
      else
        ++ans;
    }

    return ans;
  }
};

Approach

The approach taken in this solution is straightforward. We iterate through each log entry and adjust our directory count based on the command given. If we encounter ./, we simply ignore it because it means “stay where you are.” If we see ../, we decrement our count, ensuring it doesn’t go below zero (because you can’t go back from the root directory). For any other log, we increment our count, indicating we’ve entered a new directory.

Time and Space Complexity

  • Time Complexity: O(n), where n is the number of logs. We traverse the list of logs once.
  • Space Complexity: O(1), as we are using a constant amount of space for our answer variable.

Real-World Example

Imagine you’re at a party, and you keep getting lost in the house. Each time someone tells you to go to the kitchen, you’re entering a new room. If someone says, “Go back to the living room,” you’re retracing your steps. At the end of the night, you want to know how many new rooms you’ve explored. This problem is just like that, but instead of rooms, we have directories!

Similar Problems

2-Sum Solution in C++