← Back to Leo Academy Masterclass

Problem #71: Simplify Path

Medium Stack

Intuition & Strategy Breakdown

Split path by '/' and use a stack. Push valid directory names, ignore empty strings and '.', pop from stack on '..', then join remaining names with '/'.

Python Solution

def simplifyPath(path: str) -> str:
    stack = []
    for part in path.split("/"):
        if part == "..":
            if stack:
                stack.pop()
        elif part and part != ".":
            stack.append(part)
    return "/" + "/".join(stack)

Java Solution

class Solution {
    public String simplifyPath(String path) {
        Deque stack = new LinkedList<>();
        for (String part : path.split("/")) {
            if (part.equals("..")) {
                if (!stack.isEmpty()) stack.pop();
            } else if (!part.isEmpty() && !part.equals(".")) {
                stack.push(part);
            }
        }
        StringBuilder res = new StringBuilder();
        while (!stack.isEmpty()) {
            res.append("/").append(stack.pollLast());
        }
        return res.length() == 0 ? "/" : res.toString();
    }
}
Watch Interactive Video on Leo Academy Main App