progress

~/problems / Stacks / Stack: path parsing

Simplify Path

On a phone? Coding is easier on a laptop: email this problem to yourself . Meanwhile: quiz this topic or play this problem's boss fight .

Write simplify_path(path) -> str that turns an absolute Unix-style path into its canonical form.

The input always starts with /. Runs of slashes act like one /; . means "this directory" and is dropped; .. goes up one directory (up from the root stays at the root). Any other name, even ... or ..a, is an ordinary directory.

The canonical form starts with a single /, separates names with single slashes, has no trailing slash (unless it is just /), and has no . or .. entries.

simplify_path("/usr//local/./bin/")      # "/usr/local/bin"
simplify_path("/a/b/../../../c")         # "/c"
simplify_path("/../")                    # "/"
simplify_path("/x/.../y/..")             # "/x/..."

Constraints: 1 <= len(path) <= 3000; only letters, digits, ., _ and /.

Show hint

split on / and keep the directory names on a stack.

Topic: Stack: path parsing. Resolve ., .. and symlinks with a stack.

Read the visual guide
0:00
Ctrl ' run · Ctrl ↵ submit
esc