medium +20 pts

Simplify Path

Canonicalize a Unix-style absolute file path by resolving '.' and '..' segments.

Given an absolute path for a Unix-style file system (starting with '/'), simplify it to its canonical form. The rules are: - A single period '.' represents the current directory and must be ignored. - A double period '..' moves up one directory level. If '..' appears at the root, it remains at the root (do not go above '/'). - Consecutive slashes '/' are treated as a single slash. - The canonical path must start with a single slash '/', directories are separated by exactly one slash, and must not end with a slash (unless it is the root '/'). Implement the function `simplify_path(path: str) -> str` that returns the simplified canonical form of the input `path`. The input will always be an absolute path (starting with '/').

Constraints

The length of `path` is between 1 and 3000. `path` consists of English letters, digits, period '.', slash '/', or underscore '_'.

Example

>>> simplify_path("/home/")
'/home'
>>> simplify_path("/../")
'/'
>>> simplify_path("/home//foo/")
'/home/foo'
>>> simplify_path("/a/./b/../../c/")
'/c'
20 points ~25 min

Recent Submissions

No submissions yet — hit Run Tests to try!

Hints

Split the path by '/' to obtain its components.
Use a stack to keep directories. Process each component: ignore empty and '.'; for '..' pop if stack is not empty; otherwise push.
Join the stack with '/' and prepend a leading '/' — if the stack is empty, return '/'.
Be careful with edge cases like '..' at the root and multiple slashes.
Python 3
All tests passed!
Test Results
Press Ctrl+Enter or click Run Tests to execute your code.