Simplify Path Solution in Python

Problem Description

Ah, the classic “Simplify Path” problem! It’s like trying to find your way out of a maze after a night of heavy partying. You know you started at home, but somehow you ended up in a place that looks suspiciously like your neighbor’s garden. The task is to take a Unix-style file path and simplify it. You know, remove all the unnecessary parts like . (which means “stay here”) and .. (which means “go back one level”).

Imagine you’re trying to navigate through a messy closet. You have clothes everywhere, and every time you try to grab something, you end up knocking over a pile of shoes. The goal is to get to your favorite shirt without tripping over the chaos.

Code Solution


class Solution:
    def simplifyPath(self, path: str) -> str:
        stack = []

        for str in path.split('/'):
            if str in ('', '.'):
                continue
            if str == '..':
                if stack:
                    stack.pop()
            else:
                stack.append(str)

        return '/' + '/'.join(stack)

Approach

The approach here is straightforward. We use a stack to keep track of the valid directory names. As we split the path by /, we check each part:

  • If it’s empty or a dot (.), we ignore it.
  • If it’s a double dot (..), we pop the last directory from the stack (if there is one).
  • Otherwise, we push the directory onto the stack.

Finally, we join the stack back into a string, prefixed with a / to represent the root directory.

Time and Space Complexity

Time Complexity: O(N), where N is the length of the input path. We traverse the path once.

Space Complexity: O(N) in the worst case, where all parts of the path are valid directories and stored in the stack.

Real-World Example

Think of it like cleaning up your digital files. You have folders within folders, and sometimes you accidentally create a shortcut that leads you back to the same folder. The “Simplify Path” function helps you get to the main folder without all the clutter.

Similar Problems

3-Sum Solution in Python