Skip to content
BytePatterns

Simplify a Unix Path

MediumStacks & Queues#stack#string-parsing~20m

Problem

Given an absolute Unix-style path, return its simplest equivalent form. In the input, . means the current directory, .. means the parent directory (the parent of the root is the root), and several slashes in a row count as one. Any other name, including ..., is an ordinary directory. The result must start with a single slash, separate names with single slashes and not end with a slash unless it is the root itself.

Examples

Input:  path = "/a/./b/../../c/"
Output: "/c"
Why:    enter a, stay, enter b, leave b, leave a, enter c
Input:  path = "/home//user/.../docs/"
Output: "/home/user/.../docs"
Why:    the double slash collapses, and three dots is just a directory name
Input:  path = "/../"
Output: "/"
Why:    edge case, going up from the root stays at the root

Hints

0 / 3

Stuck on the idea rather than the code? Stack Basics covers it.