LeetCode 71: Simplify Path Solution

Master LeetCode problem 71 (Simplify Path), a medium challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.

71. Simplify Path

Problem Explanation

Explanation

To simplify the given absolute path, we can use a stack data structure. We split the path by '/' and process each component. If the component is '..', we pop from the stack. If the component is not '.' or empty, we push it onto the stack. Finally, we construct the simplified path using the elements in the stack.

  • Time complexity: O(n) where n is the length of the input path
  • Space complexity: O(n) for the stack

Solution Code

class Solution {
    public String simplifyPath(String path) {
        Stack<String> stack = new Stack<>();
        String[] components = path.split("/");

        for (String component : components) {
            if (component.equals("..")) {
                if (!stack.isEmpty()) {
                    stack.pop();
                }
            } else if (!component.equals(".") && !component.isEmpty()) {
                stack.push(component);
            }
        }

        return "/" + String.join("/", stack);
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 71 (Simplify Path)?

This page provides optimized solutions for LeetCode problem 71 (Simplify Path) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.

What is the time complexity of LeetCode 71 (Simplify Path)?

The time complexity for LeetCode 71 (Simplify Path) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 71 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 71 in Java, C++, or Python.

Back to LeetCode Solutions