Simplify Path
Simplify Path is LeetCode 71 (Medium). You get an absolute Unix-style path that starts with /. Return its simplified, canonical form.
.means the current directory and..means the parent directory.- Several slashes in a row act as one slash.
- Any other run of periods, like
..., is an ordinary file or directory name.
The result starts with exactly one /, puts exactly one / between names, has no trailing /, and contains no . or ...
- 1 <= path.length <= 3000
- path consists of English letters, digits, period '.', slash '/' or '_'.
- path is a valid absolute Unix path.
Intuition
Reading the path left to right is like walking through folders. Entering a folder adds a name to the end of where you are, and .. takes back the most recent name only. Adding at one end and removing from the same end is a stack.
Splitting on / gives the parts. Empty parts (from // or the leading and trailing slash) and . change nothing. A .. pops one name if there is one; at the root there is nothing above, so it does nothing. When the walk ends, the stack holds the folders from the root down, so joining them with / gives the answer.
A sequence of steps where one kind of step cancels the most recent unfinished step. Undo history, matching brackets and "backspace" string problems all reduce to the same push-and-pop on a stack.
Approach
Before reading on, simplify /a/./b/../../c/ by hand and write down where you are after each part. Notice which earlier part each .. cancels, and what the empty parts between slashes do.
Split the path on slashes
path.split("/") turns /a//b/ into ["", "a", "", "b", ""]. The empty strings come from the leading slash, the double slash and the trailing slash, so skipping them handles all three cases at once.
Skip empty parts and `.`
Neither one moves you: an empty part is an extra slash, and . names the folder you are already in.
Pop on `..`, but only when the stack has a name
.. goes up one level, which removes the last folder you entered. At the root the stack is empty and .. is simply ignored, because the root has no parent.
Push every other part as a name
Anything else, including ... or a.b, is a folder or file name, so it goes on top of the stack.
Join the stack
Return "/" + "/".join(stack). The stack lists folders from the root down. An empty stack gives "/", which is exactly the root.
Code in Python, C++ and Java
Common pitfalls
Folding the empty-stack check into the .. test
if part == ".." and stack:
stack.pop()
elif part not in ("", "."):
stack.append(part)if part == "..":
if stack:
stack.pop()
elif part not in ("", "."):
stack.append(part)When the stack is empty, .. fails the first test and falls through to the push, so it is stored as a folder name. On /../ the wrong version returns /.. instead of /.
Treating every part made of dots as special
if set(part) == {"."}:
stack.pop()if part == "..":
if stack:
stack.pop()Only exactly one dot and exactly two dots are special. /a/.../b must return /a/.../b, because ... is an ordinary name.
Returning an empty string for the root
return "".join("/" + name for name in stack)return "/" + "/".join(stack)
When every name cancels, as in /a/.., the stack is empty and the wrong version returns "". The canonical path of the root is "/".
Edge cases
.. than folders, such as /a/../../bThe second .. meets an empty stack and is ignored, so the result is /b.
Complexity
path. Splitting, the loop and the final join each touch every character a constant number of times. The parts and the stack together hold at most n characters.Simplify Path FAQ
Can I just call os.path.normpath in Python?
Not safely. POSIX keeps exactly two leading slashes as special, so posixpath.normpath("//a") returns //a, while this problem expects /a. Interviewers also want the stack logic, not a library call.
Can I solve it without split, in one pass over the characters?
Yes. Walk the string, collect characters into a name until the next /, then apply the same three rules to that name. Add one final check after the loop for a name that runs to the end. The cost is still O(n); it only saves building the list of parts.