Simplify Path
You're given path, an absolute path in a Unix-style file system that always starts with /. Return its simplified canonical form.
The rules for reading the path:
.means the current directory, so it can be dropped...means the parent directory. Going up from the root stays at the root.- Several slashes in a row, like
//, act as one slash. - Any other name, including
..., is a regular directory name.
The canonical path starts with a single /, separates directory names with single slashes, doesn't end with / (unless it's just the root) and contains no . or .. entries.
Example 1
Input: path = "/home/user/Documents/../Pictures" Output: "/home/user/Pictures"
.. steps back out of Documents before entering Pictures.
Example 2
Input: path = "/../" Output: "/"
The root has no parent, so .. leaves you at /.
Constraints
1 <= path.length <= 3000pathcontains English letters, digits,.,/and_.pathis a valid absolute Unix path.
Approach
Splitting the path on / turns it into a sequence of moves. Empty pieces come from repeated or trailing slashes, and . means stay put, so both are skipped. A name moves one level deeper, and .. undoes the most recent move.
That last-in, first-out behavior is exactly a stack. Push each directory name, pop on .. (unless the stack is already empty, which means you're at the root) and ignore everything else. The stack then holds the canonical path from the root down. Join it with / and add the leading slash.
Steps
- Split
pathon/. - For each piece, skip it if it's empty or
.. - If it's
.., pop the stack when it isn't empty. - Otherwise push the name.
- Return
/followed by the stack's names joined with/.
def simplify_path(path: str) -> str:
stack = [] # directory names on the way from the root
for part in path.split("/"):
if part == "" or part == ".":
continue # empty from repeated slashes, or "stay here"
if part == "..":
if stack:
stack.pop() # go up one level; the root has no parent
else:
stack.append(part)
return "/" + "/".join(stack)Complexity
- Time:
O(n), wherenis the length ofpath. Splitting and joining each touch every character once. - Space:
O(n)for the pieces and the stack.
Common mistakes
- Treating
...or..aas special. Only exactly.and..are. - Popping from an empty stack on
..at the root. - Returning an empty string instead of
/when the stack ends up empty.