Skip to main content

Simplify Path

MediumPremium

You're given path, an absolute path in a Unix-style file system that always starts with /. Return its simplified canonical form.

The rules for reading the path:

  • . means the current directory, so it can be dropped.
  • .. means the parent directory. Going up from the root stays at the root.
  • Several slashes in a row, like //, act as one slash.
  • Any other name, including ..., is a regular directory name.

The canonical path starts with a single /, separates directory names with single slashes, doesn't end with / (unless it's just the root) and contains no . or .. entries.

Example 1

Input: path = "/home/user/Documents/../Pictures" Output: "/home/user/Pictures"

.. steps back out of Documents before entering Pictures.

Example 2

Input: path = "/../" Output: "/"

The root has no parent, so .. leaves you at /.

Constraints

  • 1 <= path.length <= 3000
  • path contains English letters, digits, ., / and _.
  • path is a valid absolute Unix path.