Simplify Path
MediumTop Interview 150 StackPatreonTinkoffMetaGrabVisaProblem
You are given path, an absolute Unix-style path that always starts with a slash.
Rewrite it in its shortest canonical form and return that string.
The rules:
- A single dot
.means the current folder, so it can be dropped. - Two dots
..mean the parent folder. Going up from the root stays at the root. - Several slashes in a row act like one slash.
- Any other piece, including
...or..a, is an ordinary folder name.
The result starts with a single slash, separates folder names with single slashes, and has no
trailing slash (unless the result is just the root /).
Constraints
- 1 ≤ path.length ≤ 3000
- path contains English letters, digits, '.', '/' and '_'
- path begins with '/'
Examples: pick one to animate
Solutions
TimeO(n)
SpaceO(n)
Time: Splitting reads each character once, every piece is pushed or popped at most once, and the final join is linear.
Space: The pieces and the stack together hold at most n characters.
Split the path on / and walk the pieces. Skip empty pieces and .;
on .. pop the last folder if there is one; push every other piece. The stack, joined with
slashes, is the answer.