There is a file system that 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.
Example 1:
Input: logs = ["d1/","d2/","../","d21/","./"]
Output: 2Explanation: After all the log operations, use this change folder operation "../" 2 times and go back to the main folder.
Example 2:
Input: logs = ["d1/","../","../","../"]
Output: 0Example 3:
Input: logs = ["d1/","d2/","../","d3/","../","d4/","../","d5/"]
Output: 2Constraints:
1 <= logs.length <= 10002 <= logs[i].length <= 10logs[i] contains lowercase English letters, digits, '.', and '/'.logs[i] follows the format described in the statement.Before attempting this problem, you should be comfortable with:
A file system path can be naturally modeled using a stack. Moving into a folder pushes onto the stack, while moving to the parent folder pops from the stack. The operation "./" does nothing (stay in current folder). At the end, the stack's size represents how deep we are from the main folder, which equals the minimum operations needed to return.
"../", pop from the stack if it is not empty (move to parent)."./", do nothing (stay in current folder).We do not actually need to store the folder names since we only care about the depth. A simple counter can track how many levels deep we are. Moving into a folder increments the counter, moving to parent decrements it (but never below 0 since we cannot go above the main folder), and "./" leaves it unchanged.
0."./", skip (no change in depth)."../", decrement the counter but ensure it does not go below 0.When processing "../", you must ensure the depth does not go below zero. Going above the main folder is impossible, so decrementing when already at depth 0 produces wrong results.
# Wrong: depth can become negative
if log == "../":
depth -= 1
# Correct: clamp at zero
if log == "../":
depth = max(0, depth - 1)The operation "./" means stay in the current folder and should not change the depth. Treating it like a folder name and incrementing depth is a common mistake.
# Wrong: treating "./" as a folder
if log != "../":
depth += 1 # This incorrectly increments for "./"
# Correct: explicitly skip "./"
if log == "./":
continue
elif log == "../":
depth = max(0, depth - 1)
else:
depth += 1