A system logs the operations performed on a folder with a series of strings. Each string represents an operation that is one of the following:
"../"
: Move to the parent folder. (If you are already in the main folder, you stay in the main folder.)"./"
: Stay in the current folder."x/"
: Move to a child folder named x
. This is guaranteed to be a valid folder name.You are starting in the main folder, and your task is to determine the minimum number of operations required to go back to the main folder after performing all the operations in the log.
Given an array logs
where logs[i]
is a string representing the i-th
operation, return the minimum number of operations needed to go back to the main folder.
0
?
0
.depth
to keep track of the current folder’s depth, initialized to 0
."../"
, decrease the depth
by 1
if it’s greater than 0
(because you can’t go above the main folder)."./"
, do nothing as it means staying in the current folder."x/"
, increase the depth
by 1
because it means moving to a child folder.depth
will represent the minimum operations required to return to the main folder (which is just the value of depth
itself).def minOperations(logs):
depth = 0
for log in logs:
if log == "../":
if depth > 0:
depth -= 1
elif log == "./":
continue
else: # it means "x/"
depth += 1
return depth
Time Complexity: The time complexity of this solution is (O(n)), where (n) is the number of elements in the logs
array. This is because we are iterating over each log once.
Space Complexity: The space complexity is (O(1)) as we are using only a single integer variable (depth
), whose space usage does not depend on the input size.
This efficient approach ensures that we handle the operations in linear time with constant extra space.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?