LeetCode 71: Simplify Path — Python Solution

Solve LeetCode 71: Simplify Path in Python with a canonical path stack approach. The key is to make the state invariant explicit, so the implementation and complexity follow naturally.

This guide paraphrases the task and does not reproduce LeetCode’s prompt. Use the official page for the complete statement, examples, constraints, and submission runner.

DifficultyMedium
TopicStack
Reusable patterncanonical path stack
ComplexityO(n) time and O(n) space

What the problem is testing

Ignore empty and dot components, pop on double-dot when possible, and push ordinary directory names.

Algorithm

  1. Ignore empty and dot components, pop on double-dot when possible, and push ordinary directory names.
  2. Maintain this invariant: The stack is the canonical absolute path for all processed components.
  3. Continue until every input item or reachable state has been resolved, then return the accumulated result.

Python solution

from collections import Counter, defaultdict, deque, OrderedDict
import random

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

Why this is correct

The proof follows the maintained state: The stack is the canonical absolute path for all processed components. Each iteration preserves that claim while permanently resolving at least one position, node, interval, or search state. When the loop or recursion ends, every candidate required by the problem has therefore been included or ruled out, so the returned value is correct.

Complexity

O(n) time and O(n) space. The stated auxiliary space excludes the returned output unless the output is the data structure being built.

Edge cases

Attempts to move above root have no effect; repeated slashes are ignored.

Tested reference code

This implementation is included in the site’s downloadable 100-solution Python library. The complete suite compiles every solution and runs a behavioral assertion for every problem before publication.


Browse the searchable 100 LeetCode Python Solutions hub. Previous: 20. Valid Parentheses · Next: 155. Min Stack