Simplify Path

Medium#71one step back

You get an absolute Unix-style path. Write it the shortest way: one "/" between folders, none at the end, no "." (the current folder) and no ".." (the folder above, which at the root stays at the root). Our example: "/../srv//www/./tmp/../app/" becomes "/srv/www/app".

input
path: an absolute Unix path. . is the directory itself, .. its parent, several / in a row are one; any other part, ... too, is a name.
returns
The same path in canonical form: it starts with one /, names are separated by one /, there is no / at the end (unless the path is /), no . and no ... .. at the root stays at the root.
constraints
  • 1 ≤ path.length ≤ 3000
  • path: English letters, digits and the characters . / _
  • path starts with /
our 15 tests keep to them
examples
Open a test in the tests panel: it shows the input and the expected answer.
/**
 * @param {string} path
 * @return {string}
 */
function simplifyPath(path) {

}
Ctrl ↵
format
reset

saved in this browser

15 tests · limit 3 s

Stuck?

See the solution run step by step on our example, then why it works and its complexity.

Watch the walkthrough →

Next: more stack problems

Pattern “Stack” →

The problem and its statement belong to LeetCode. Here are our own retelling, example and solution. Patterns Hero is not affiliated with LeetCode.