We split the path by / and use a stack to process each component.
- Split the string by
/. - Iterate through components:
- If component is
..: pop from stack if stack is not empty (go up). - If component is
.or empty: do nothing. - Else: push the component onto the stack.
- If component is
- Join the stack elements with
/and prepend/.
- Time Complexity: O(N).
- Space Complexity: O(N).
def simplify_path(path):
stack = []
components = path.split("/")
for c in components:
if c == "..":
if stack:
stack.pop()
elif c == "." or not c:
continue
else:
stack.append(c)
return "/" + "/".join(stack)