We split the path by / and use a stack to process the components. .. pops from the stack, while . and empty strings are ignored.
- Split
pathusing/. - Initialize
stack = []. - For each
partin components:- If
part == '..',pop()from stack if not empty. - Else if
partis not.and not empty,push(part).
- If
- Return
'/' + '/'.join(stack).
- Time Complexity: O(N).
- Space Complexity: O(N).
def simplify_path(path):
stack = []
parts = path.split("/")
for p in parts:
if p == "..":
if stack:
stack.pop()
elif p == "." or not p:
continue
else:
stack.append(p)
return "/" + "/".join(stack)