KatInterview

71. Simplify Path

MediumSolutions in Python, Java, C++, TypeScript

Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.

Approach

The problem requires us to simplify a Unix-style absolute path into its canonical form. The key challenges involve handling special directory notations like . (current directory), .. (parent directory), and multiple slashes //. The final path must adhere to a strict format: starting with a single /, directories separated by a single /, and no trailing slash unless it's the root directory itself (/).

Solution

Simplify Path in Python

class Solution:
    def simplifyPath(self, path: str) -> str:
        # Use a list to act as a stack for the canonical path's directories.
        stack = []
        
        # Split the path by '/' to get the directory/file components.
        components = path.split('/')
        
        # Process each component.
        for component in components:
            if component == '..':
                # If '..', go up one level by popping from the stack if it's not empty.
                if stack:
                    stack.pop()
            elif component and component != '.':
                # If it's a valid name (not empty and not '.'), push it to the stack.
                # An empty component results from multiple slashes (e.g., '//') or leading/trailing slashes.
                stack.append(component)
            
        # Join the components in the stack with '/' and prepend a leading '/' to form the canonical path.
        # If the stack is empty, the path is the root directory '/'.
        return '/' + '/'.join(stack)

Simplify Path in Java

class Solution {
    public String simplifyPath(String path) {
        // Deque is used as a stack to store directory names.
        // ArrayDeque is generally preferred over Stack in modern Java.
        Deque<String> stack = new ArrayDeque<>();
        
        // Split the path by one or more slashes.
        String[] components = path.split("/");

        for (String component : components) {
            if (component.equals("..")) {
                // If we encounter '..', pop from the stack if it's not empty.
                if (!stack.isEmpty()) {
                    stack.pollLast();
                }
            } else if (!component.isEmpty() && !component.equals(".")) {
                // If it's a valid directory name (not empty and not '.'), push it onto the stack.
                // Empty strings result from leading/trailing/multiple slashes.
                stack.addLast(component);
            }
            // Ignore '.' (current directory) and empty strings.
        }

        // If the stack is empty, it means we are at the root directory.
        if (stack.isEmpty()) {
            return "/";
        }

        // Reconstruct the path from the stack.
        StringBuilder result = new StringBuilder();
        for (String dir : stack) {
            result.append("/").append(dir);
        }
        
        return result.toString();
    }
}

Simplify Path in C++

class Solution {
public:
    string simplifyPath(string path) {
        std::vector<std::string> components;
        std::stringstream ss(path);
        std::string item;

        // Split the path by '/' and process each component.
        while (std::getline(ss, item, '/')) {
            if (item == "" || item == ".") {
                // Ignore empty components (from multiple slashes) and '.' (current directory).
                continue;
            } else if (item == "..") {
                // If '..', go up one level by popping from the stack if not empty.
                if (!components.empty()) {
                    components.pop_back();
                }
            } else {
                // This is a valid directory name, push it to our path stack.
                components.push_back(item);
            }
        }

        // Reconstruct the canonical path from the components.
        if (components.empty()) {
            return "/";
        }

        std::string result = "";
        for (const auto& dir : components) {
            result += "/" + dir;
        }

        return result;
    }
};

Simplify Path in TypeScript

function simplifyPath(path: string): string {
    // Use an array as a stack to build the canonical path.
    const stack: string[] = [];
    
    // Split the path by '/' to get individual components.
    const components = path.split('/');

    // Iterate over each component.
    for (const component of components) {
        if (component === '..') {
            // If component is '..', go up one level by popping from the stack, if not empty.
            if (stack.length > 0) {
                stack.pop();
            }
        } else if (component && component !== '.') {
            // If component is a valid directory/file name (not empty and not '.'), push it.
            // Empty strings result from multiple, leading, or trailing slashes.
            stack.push(component);
        }
        // Ignore empty strings and '.'
    }

    // Join the stack components with '/' and prepend a leading '/' for the final path.
    // If the stack is empty, this results in just '/'.
    return '/' + stack.join('/');
};

Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.

LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.