SDE & MLE Prep

71. Simplify Path

Problem

Convert an absolute Unix-style path to its canonical form: . means the current directory, .. goes up one level (staying at the root if already there), repeated slashes count as one, and any other name (including ...) is a directory. The result starts with a single /, has single slashes between names and no trailing slash.

Example: "/home//foo/" → "/home/foo"; "/../" → "/"; "/a/./b/../../c/" → "/c"

Split on /. Skip "" and "."; ".." pops; anything else pushes. Join with /.

Complexity: O(n).

class Solution:
    def simplifyPath(self, path: str) -> str:
        st = []
        for part in path.split("/"):
            if part == "..":
                if st:
                    st.pop()
            elif part and part != ".":
                st.append(part)
        return "/" + "/".join(st)