Simplify Path

Medium StackString

Problem

Given an absolute Unix-style path, return its canonical form. - . → current directory (skip) - .. → parent directory (pop one) - // (and more) collapse to a single / - anything else is a directory name The result starts with /, has no trailing / (except the root itself), and contains no . or ...

Example 1 Input: "/home/" Output: "/home"
Example 2 Input: "/home//foo/" Output: "/home/foo"
Example 3 Input: "/a/./b/../../c/" Output: "/c"
Example 4 Input: "/../" Output: "/"

Constraints

Approach — Stack

This is a Stack problem. The idea: scan the input once, pushing work onto a stack and popping when the top can be resolved, so the stack always reflects what's still open. Work through the reference code below line by line, then re-derive it yourself in the editor — that's how the pattern sticks.

Complexity: O(n) time, O(n) space.

Solution code

Python

class Solution:
    def simplifyPath(self, path):
        st = []
        for part in path.split('/'):
            if part == '' or part == '.':
                continue
            if part == '..':
                if st:
                    st.pop()
            else:
                st.append(part)
        return '/' + '/'.join(st)

Java

import java.util.ArrayDeque;
import java.util.Deque;

class Solution {
    public String simplifyPath(String path) {

        // Initialize a stack
        Deque<String> stack = new ArrayDeque<>();
        String[] components = path.split("/");

        // Split the input string on "/" as the delimiter
        // and process each portion one by one
        for (String directory : components) {

            // A no-op for a "." or an empty string
            if (directory.equals(".") || directory.isEmpty()) {
                continue;
            } else if (directory.equals("..")) {

                // If the current component is a "..", then
                // we pop an entry from the stack if it's non-empty
                if (!stack.isEmpty()) {
                    stack.pop();
                }
            } else {

                // Finally, a legitimate directory name, so we add it
                // to our stack
                stack.push(directory);
            }
        }

        // Stich together all the directory names together
        StringBuilder result = new StringBuilder();
        while (!stack.isEmpty()) {
            result.insert(0, "/" + stack.pop());
        }

        return result.length() == 0 ? "/" : result.toString();
    }
}

Practice it

Reading a solution isn't the same as being able to write it under pressure. Open this problem in the in-browser editor, hide the solution, and solve it from scratch — your code runs against real test cases instantly.

Solve Simplify Path interactively → ← All solutions