Skip to content

Simplify Path

MediumStack
Decode it first. Clues, constraints, pattern and plan before any code.

Given an absolute Unix-style file path path (it starts with /), return its simplified canonical form. The rules:

  • . means the current folder and can be dropped.
  • .. means go up one folder. Going up from the root / stays at the root.
  • Several slashes in a row, like //, count as one.
  • Any other name, including ..., is a normal folder name.

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

"/home/"                            →  "/home"
"/home//foo/"                       →  "/home/foo"
"/home/user/Documents/../Pictures"  →  "/home/user/Pictures"
"/../"                              →  "/"

Constraints

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