Tensorum
LeetCode 71 · Stack Simulation / String Processing

Simplify Path

LeetCode 71 · Medium · solution, intuition & step-by-step walkthrough

Stack of directory names.

MediumStringStack
0 msruntime · beats 100%
19.3 MBmemory · beats 11%
1approach
2accepted runs · last 15 Mar 2026

This is how I solved Simplify Path (LeetCode 71), a medium problem from the Stack Simulation / String Processing pattern. Below: the intuition, the approach step by step, my accepted Python code, animated test cases and a line-by-line debugger.

Intuition

Split the path on '/' and process the pieces with a stack: '..' pops a directory, '.' and empty pieces do nothing, anything else is a directory name to push.

Approach

  1. 1

    Split by '/'.

  2. 2

    Skip '' and '.'.

  3. 3

    '..' → pop if possible.

  4. 4

    Push other names; join with '/' and prefix '/'.

How I solved it

Stack of componentsPythonO(n) time
class Solution:
    def simplifyPath(self, path: str) -> str:
        #/.../a/../b/c/../d/./
        #/directory_name/ [a/..] - >/directory_name/
        #/directory_name/b/c/.. ->/directory_name/b/
        #/directory_name/b/d/. -> /.../b/d

        #intuition is - 
        #/d/./ -> /d
        #if it's single dot (.) we just ignoring . and taking the previous path /d
        #/user/Documents/.. ->/user
        #if it's a double dot then we are removing Documents

        #approach
        #have a stack
        #split string by /
        #if cur string is . no need to do anything
        #if cur string is .. pop from stack
        #rest - add to stack
        #finally join by / and return 
        stack =[]
        components = path.split("/")
        for component in components:
            if component=="." or component=="":
                continue
            elif component=="..":
                if len(stack)>0:
                    stack.pop()
            else:
                stack.append(component)
        return "/"+"/".join(stack)
Loading the step-through…

Simplify Path — FAQ

What is the intuition behind Simplify Path?

Split the path on '/' and process the pieces with a stack: '..' pops a directory, '.' and empty pieces do nothing, anything else is a directory name to push.

How do you solve Simplify Path (LeetCode 71)?

1. Split by '/'. 2. Skip '' and '.'. 3. '..' → pop if possible. 4. Push other names; join with '/' and prefix '/'.

What is the time and space complexity of Simplify Path?

Time: O(n). Space: O(n). (Accepted approach: Stack of components.)

What are common mistakes in Simplify Path?

'...' is a valid directory name, not a parent reference.