Simplify Path

Medium

Topics
StringStack

Given an absolute Unix-style path path, return its simplified canonical path. Handle . (current), .. (parent), and redundant slashes.

Example 1

partshome
resulthome
Splitting on / makes the rest mechanical: . and empty parts are dropped, .. pops, and anything else pushes. Popping an empty stack must be a no-op, since the root has no parent. Result: /home.
Chips are the path components before and after simplification.
Input:  path = "/home/"
Output: "/home"

Example 2

parts..
result/
Input:  path = "/../"
Output: "/"

Example 3

partsa.b....c
resultc
Input:  path = "/a/./b/../../c/"
Output: "/c"

Constraints

  • 1 <= path.length <= 3000
  • path begins with a single slash.
Editorial — intuition, approach, complexity and pitfalls

Intuition

Split on / and the path becomes a list of segments, most of which are directory names to keep. Three segment kinds are special: the empty string (from a doubled or trailing slash) and . are both no-ops, and .. pops the previous directory.

A stack of kept segments makes the whole thing one pass. The leading slash is restored at the end, and because the path is absolute, a .. at the root is simply ignored rather than an error.

Approach

  1. Split the path on /.
  2. Skip empty segments and ..
  3. On .., pop if the stack is non-empty.
  4. Otherwise push the segment.
  5. Return / joined with the stack.

Dry Run

"/home/"            ->  "/home"          trailing slash gives an empty segment
"/../"              ->  "/"              .. at the root is ignored
"/home//foo/"       ->  "/home/foo"      the doubled slash gives an empty segment
"/a/./b/../../c/"   ->  "/c"             . skipped, then two pops
"/..."              ->  "/..."           three dots is an ordinary name
"/a/../../b"        ->  "/b"             the second .. pops nothing

Complexity

  • Time — O(n): the split is linear and each segment is handled once.
  • Space — O(n) for the segment list and the stack.

Common Pitfalls

  • Treating ... or any longer run of dots as a parent reference. Only exactly .. is special; ... is a legal directory name, and this is the case most often missed.
  • Popping on .. without checking the stack, which throws at the root. On an absolute path the root has no parent, so the operation is a no-op.
  • Hand-rolling the slash handling with an index walk and getting the doubled-slash case wrong. Splitting and discarding empty segments handles redundant and trailing slashes in one rule.
  • Joining without the leading /, or emitting a trailing one. The canonical form starts with exactly one slash and ends without one, except for the root itself which is just /.
  • Returning the empty string when everything pops. The root is /, which the "/" + join(...) form produces for free.

Full Solution — all languages

class Solution:
    def simplifyPath(self, s):
        stack = []
        for part in s.split("/"):
            if part == "" or part == ".":
                continue
            if part == "..":
                if stack: stack.pop()
            else:
                stack.append(part)
        return "/" + "/".join(stack)
SensAI
Beta
Tap the mic to stop voice mode