71. Simplify Path

StringStack

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
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);
    }
}

Code Editor (Testing phase)

Improve Your Solution

Use the editor below to refine the provided solution. Select a programming language and try the following:

  • Add import statement if required.
  • Optimize the code for better time or space complexity.
  • Add test cases to validate edge cases and common scenarios.
  • Handle error conditions or invalid inputs gracefully.
  • Experiment with alternative approaches to deepen your understanding.

Click "Run Code" to execute your solution and view the output. If errors occur, check the line numbers and debug accordingly. Resize the editor by dragging its bottom edge.