Tidy a Folder Path

EasyStack≈ 20 min

You are given an absolute folder path, starting with /, as a computer would accept it. Return the same location written in its tidy form:

  • a single . means "this folder", and is dropped;
  • .. means "the folder above", and cancels the folder before it; at the root / there is nothing above, so it does nothing;
  • several slashes in a row count as one, and there is no slash at the end;
  • the tidy path starts with a single /; the root on its own is "/".

Any other piece between slashes is a folder name, even one made of dots, like ... or ..file.

Examples

text
path = "/home/ana/../ben/./notes/"   →  "/home/ben/notes"
path = "/../"                        →  "/"
path = "//usr///local/bin"           →  "/usr/local/bin"
path = "/a/b/../../c/.."             →  "/"

In the first example .. cancels ana, and . is dropped.

Constraints

  • Between 1 and 30,000 characters: letters, digits, ., _, - and /. The path starts with /.
  • Aim for O(n): read the path once.
Sound off. Turn on for key clicks and a chime when the tests pass.Inline suggestions off. Recommended while you are learning. Turn on to complete words as you type.
Console
›Run to see what your code prints

Run checks the 4 visible cases here, in your browser. Submit runs all 9 on the judge, 5 of them hidden, and measures how your solution scales.