You get path, an absolute path in a Unix-style file system: it always starts with /. Return the shortest equivalent path, its canonical form.
In the input, . means the folder you are in, .. means its parent (and at the root it stays at the root), and several slashes in a row act like one. Any other run of dots, such as ..., is just a folder name.
The answer starts with a single /, has exactly one / between names, has no . or .. parts, and does not end with / unless it is the root itself.
Example 1
Input: path = "/docs/./img//../notes/" Output: "/docs/notes" Why: "." stays put, ".." undoes img, "//" is one slash
2 more examples and the constraints
Example 2
Input: path = "/../../x" Output: "/x" Why: you cannot climb above the root
Example 3
Input: path = "/a/.../b/.." Output: "/a/..." Why: "..." is a folder name; ".." leaves b
Constraints
- 1 ≤ length of path ≤ 3,000
- path holds English letters, digits,
.,/and_ - path is a valid absolute path
Your turn first
Have a go on paper or in your own editor, then reveal the approaches from the simplest up.
- Rewrite until stableO(n²)
- Split + stackO(n)
The idea in one sentence
The pattern, how to spot it, and the best complexity.
Side by side
| Approach | Time | Relative work for a 3,000-character path | Verdict |
|---|---|---|---|
| Rewrite until stable | O(n²) | Works, but slow and fiddly | |
| Split + stack | O(n) | Best; one pass, easy to explain |
n = length of the path.
Edge cases to test
- Above the root. "/../../x" gives "/x": a
..at the root does nothing. - Everything cancels. "/a/b/../../.." gives "/", never an empty string.
- Dots that are names. "...", "..a" and "b.." are folders and stay in the answer.
- Only slashes. "////" is the root: "/".
- Trailing slash. "/music/" gives "/music", with no slash at the end.
Common mistakes
- Popping on
..when the stack is empty, which crashes or goes above the root. - Returning an empty string instead of "/" when every name cancels out.
- Treating any part that starts with a dot as special, so
...is dropped.
How to talk through it
- 1Clarify. What does
..do at the root? Are names like...valid? Should the answer ever end with a slash? - 2Spot the stack. Only the deepest folder ever changes, so a stack of names is the whole state.
- 3List the part types. Empty and
.are skipped,..pops, anything else pushes. - 4Code it. Split, loop with three branches, then join with a leading slash.
- 5Test out loud. Run "/../../x", "/a/b/../../.." and a path with "...".
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?