Normalize an Absolute Unix-Style File Path to Canonical Form
NVIDIASoftware Engineer · OtherLast updated
Convert an absolute Unix-style file path into canonical form by collapsing repeated slashes, dropping current-directory markers, applying parent-directory moves that stop at the root, and treating other dot-only names as ordinary directories. Tests careful string parsing and edge-case handling of path components.
You are given an absolute path in a Unix-style file system. Rewrite it in canonical form by resolving the special directory names and removing redundant separators.
Function Signature
def canonicalize_path(path: str) -> str:
Rules
- The input always starts with
/. Split it into components on/; any run of consecutive slashes counts as a single separator, and empty components are ignored. - A component equal to
.refers to the current directory and is dropped. - A component equal to
..moves up to the parent directory, removing the most recently kept name. At the root there is no parent, so..leaves the path at the root. - Every other component is an ordinary directory or file name, including names made only of periods such as
...or..... - The canonical path starts with exactly one
/, joins the kept names with single/characters, and has no trailing/. If no names remain, the result is/.
Constraints
1 <= len(path) <= 3000path[0] == "/"pathcontains only English letters, digits,.,/and_.
Examples
Example 1
Input: path = "/usr//local/./bin/"
Output: "/usr/local/bin"
The doubled slash collapses, the . component is dropped and the trailing slash is removed.
Example 2
Input: path = "/a/b/../../../c/.../d/.."
Output: "/c/..."
The first two .. components undo b and a; the third is applied at the root and has no effect. ... is an ordinary name, and the final .. undoes d.
Example 3
Input: path = "/../"
Output: "/"
Solution walkthrough is for members
Get the full walkthrough with reference code and complexity analysis, plus Kitty Coach at 300 messages a day. Hints, the code runner and community answers stay free.