Editor

Tidy a File Path

#76 · Stacks and queues · Intermediate · 65 XP · about 12 min

On Unix-style systems a path like /home//user/./docs/../music/ can be written much more cleanly. Write simplify_path(path) that returns the shortest equivalent form of an absolute path (one that starts with /).

The pieces between slashes follow these rules:

  • . means the current folder, so it can be dropped.
  • .. means the parent folder, so it cancels the folder before it. At the top level there is no parent, so it does nothing.
  • Several slashes in a row count as one.
  • Any other piece is a folder name, even one made only of dots such as ....

The result starts with a single /, separates folders with single slashes and does not end with a slash (unless the whole result is /).

Examples

simplify_path("/home//user/./docs/../music/")  # returns '/home/user/music'
simplify_path("/a/b/../../c")                  # returns '/c'
simplify_path("/../..")                        # returns '/'
simplify_path("/x/.../y/..")                   # returns '/x/...'

Constraints

  • 1 <= len(path) <= 3,000
  • path starts with / and holds letters, digits, dots, underscores and slashes.

Ready?

Accept the challenge to start writing. A small timer counts the time this page is in view.

Output appears here.