Crawler Log Folder

easy stack simulation

Problem

A file-system crawler starts in the main folder and writes one log entry per move: "x/" means it stepped into child folder x, "../" means it moved up to the parent folder (staying put if it is already in the main folder), and "./" means it stayed where it was. After replaying every log entry, return the minimum number of operations needed to get the crawler back to the main folder.

Inputlogs = ["d1/","d2/","../","d21/","./"]
Output2
The crawler ends inside d1/d21, two levels below main, so it needs two "../" moves to return.

def min_operations(logs):
    depth = 0
    for log in logs:
        if log == "../":
            depth = max(depth - 1, 0)
        elif log != "./":
            depth += 1
    return depth
function minOperations(logs) {
  let depth = 0;
  for (const log of logs) {
    if (log === "../") depth = Math.max(depth - 1, 0);
    else if (log !== "./") depth++;
  }
  return depth;
}
int minOperations(String[] logs) {
    int depth = 0;
    for (String log : logs) {
        if (log.equals("../")) depth = Math.max(depth - 1, 0);
        else if (!log.equals("./")) depth++;
    }
    return depth;
}
int minOperations(vector<string>& logs) {
    int depth = 0;
    for (string& log : logs) {
        if (log == "../") depth = max(depth - 1, 0);
        else if (log != "./") depth++;
    }
    return depth;
}
Time: O(n) Space: O(1)