LeetCode #71 Medium

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 ...

Constraints
  • 1 <= path.length <= 3000
  • path consists of English letters, digits, period '.', slash '/' or '_'.
  • path is a valid absolute Unix path.
stackstrings
Open on LeetCode ↗
02

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.

How to spot this pattern

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.

03

Approach

Try it first

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.

1

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.

2

Skip empty parts and `.`

Neither one moves you: an empty part is an extra slash, and . names the folder you are already in.

3

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.

4

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.

5

Join the stack

Return "/" + "/".join(stack). The stack lists folders from the root down. An empty stack gives "/", which is exactly the root.

04

Code in Python, C++ and Java

▶1class Solution:
▶2 def simplifyPath(self, path: str) -> str:
▶3 stack = []
▶4 for part in path.split("/"):
▶5 if part == "" or part == ".":
▶6 continue
▶7 if part == "..":
▶8 if stack:
▶9 stack.pop()
▶10 else:
▶11 stack.append(part)
▶12 return "/" + "/".join(stack)
parts after splitting on /emptya.b....cemptystackemptybottom = nearest the rootcurrent path/split on / → 8 parts
parts8
Splitting gives every piece between slashes. The leading slash, a trailing slash and any double slash each produce an empty part, so they are all handled by one rule later.
parts after splitting on /emptya.b....cemptystackemptybottom = nearest the rootcurrent path/empty part → skip
part(empty)
An empty part comes from an extra slash. It does not name a folder, so nothing changes.
parts after splitting on /emptya.b....cemptystackabottom = nearest the rootcurrent path/aenter 'a' → push
part'a'
stacka
a names a folder, so you step into it and it goes on top of the stack.
parts after splitting on /emptya.b....cemptystackabottom = nearest the rootcurrent path/a'.' is this folder → skip
part'.'
. means the folder you are already in, so the position does not move.
parts after splitting on /emptya.b....cemptystackabbottom = nearest the rootcurrent path/a/benter 'b' → push
part'b'
stacka / b
b names a folder, so you step into it and it goes on top of the stack.
parts after splitting on /emptya.b....cemptystackabpoppedbottom = nearest the rootcurrent path/a'..' → leave 'b'
part'..'
stackapopped 'b'
.. goes up one level, which undoes only the most recent folder entered: b. That folder is on top of the stack, so one pop removes it.
parts after splitting on /emptya.b....cemptystackapoppedbottom = nearest the rootcurrent path/'..' → leave 'a'
part'..'
stackemptypopped 'a'
.. goes up one level, which undoes only the most recent folder entered: a. That folder is on top of the stack, so one pop removes it.
parts after splitting on /emptya.b....cemptystackcbottom = nearest the rootcurrent path/center 'c' → push
part'c'
stackc
c names a folder, so you step into it and it goes on top of the stack.
parts after splitting on /emptya.b....cemptystackcbottom = nearest the rootcurrent path/cempty part → skip
part(empty)
An empty part comes from an extra slash. It does not name a folder, so nothing changes.
parts after splitting on /emptya.b....cemptystackcbottom = nearest the rootcurrent path/canswer: /c
result"/c"
The stack lists the folders from the root down, so joining them with one slash each and adding a leading slash gives /c.
05

Common pitfalls

Folding the empty-stack check into the .. test

✗ Wrong
if part == ".." and stack:
    stack.pop()
elif part not in ("", "."):
    stack.append(part)
✓ Right
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

✗ Wrong
if set(part) == {"."}:
    stack.pop()
✓ Right
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

✗ Wrong
return "".join("/" + name for name in stack)
✓ Right
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 "/".

06

Edge cases

More .. than folders, such as /a/../../b

The second .. meets an empty stack and is ignored, so the result is /b.

07

Complexity

Time
O(n)
Space
O(n)
n is the length of 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.
08

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.