148. Tidy the Path

A file manager receives paths typed by hand and wants to show them in a tidy canonical form. A path is read from the root folder, with parts separated by slashes. An empty part (from a doubled or a trailing slash) and a part that is just . change nothing. A part that is exactly .. moves one folder up; at the root it stays at the root. Every other part, even ... or a., is an ordinary folder name.

Return the tidy path: it starts with one slash, has single slashes between names, and has no trailing slash (the root alone is /). A path that does not start with a slash is read from the root as well. A stack of folder names does the job.

Example 1

Input:
path = "/data//logs/./2024/../old/"
Output:
"/data/logs/old"
Explanation:

data and logs are entered, the dot is skipped, 2024 is entered and then left again by .., and old is entered.

Example 2

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

The .. at the root changes nothing, and ... is a normal name, so only ... and x remain.

Constraints

1 ≤ path.length ≤ 105

path contains letters, digits, dots and slashes

How this problem is judged

Answers
Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.
Time per case
Python 2,000 msC++ 500 msJava 1,000 msJavaScript 1,000 msTypeScript 1,000 ms

Expected complexity

Time
O(n)
Space
O(n)

What the author was aiming for. Your own solution is not measured against it.

Asked in an interview

Were you asked this in an interview? Say where, anonymously.

Code
Loading the editor…