MediumPro challengePythonJavaScriptTypeScript
Strings — Simplify Path
AlgorithmsStringsStack
solve(path) — path is an absolute Unix-style path starting with /. Return its
canonical form:
- one slash between directory names, no trailing slash (except for the root
"/"); .means the current directory and is dropped;..goes up one level (and does nothing at the root);- several consecutive slashes count as one;
- any other name, including `...`, is a normal directory name.
Split on /, then process the pieces with a stack: ignore empty pieces and ., pop on.. (if the stack is not empty), push everything else. Join the stack back with /.
Examples
solve("/home/") → "/home"
solve("/home//foo/") → "/home/foo"
solve("/a/./b/../../c/") → "/c"
solve("/../") → "/"
solve("/...") → "/..."Sample tests
Test #1Trailing slash
Input: ["/home/"]
Output: "/home"
Test #2Double slash
Input: ["/home//foo/"]
Output: "/home/foo"
Test #3Dots and parents
Input: ["/a/./b/../../c/"]
Output: "/c"