LeetCode 71: Simplify Path is a Medium stack problem. This Python walkthrough develops a canonical path stack solution, ties every code decision to a concrete invariant, and includes the regression check used before publication.
This independent guide paraphrases the task rather than reproducing LeetCode’s prompt. Use the official page for the exact statement, examples, constraints, and submission runner.
| Difficulty | Medium |
|---|---|
| Topic | Stack |
| Reusable pattern | canonical path stack |
| Complexity | O(n) time and O(n) space |
Recognizing the pattern
A stack is appropriate when the newest unresolved item must be handled before older unresolved items.
For this problem specifically, ignore empty and dot components, pop on double-dot when possible, and push ordinary directory names. The invariant worth writing beside the code is: The stack is the canonical absolute path for all processed components.
Step-by-step algorithm
- Identify the input state consumed by
simplifyPath(path)and initialize the data required by the canonical path stack pattern. - Ignore empty and dot components, pop on double-dot when possible, and push ordinary directory names.
- After each update, verify the page’s central invariant: The stack is the canonical absolute path for all processed components.
- Finish only after the boundary behavior is covered: Attempts to move above root have no effect; repeated slashes are ignored.
Python solution
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)Reading the implementation
The main entry point is simplifyPath(path). The named working state includes stack; those variables make the canonical path stack state visible instead of hiding it in incidental control flow.
A single main loop advances the algorithm, which is the key reason the traversal does not revisit already resolved input unnecessarily. In concrete terms, ignore empty and dot components, pop on double-dot when possible, and push ordinary directory names.
Correctness argument
Initialization. The data structure starts with exactly the information known before any input element is processed.
Preservation. Ignore empty and dot components, pop on double-dot when possible, and push ordinary directory names. Each update records the current item without invalidating earlier decisions; consequently, the stack is the canonical absolute path for all processed components.
Termination. The traversal consumes a finite input or finite state space. At the end, the invariant covers the complete input, which is precisely the condition required for the returned result.
Complexity and trade-offs
O(n) time and O(n) space. The auxiliary-space figure excludes the returned output unless the output itself is the structure being built.
Repeated rescanning can find the same dependency without a stack, but it usually hides the nesting invariant and costs more time. That comparison is useful in an interview because it explains why the final implementation is preferable, not merely that it passes.
Regression check
The published implementation belongs to a 100-problem suite that is compiled and exercised behaviorally before deployment.
One reference assertion from that suite is shown below. It targets the normal path while the edge conditions in the next section cover the failure-prone boundaries.
assert Solution().simplifyPath("/home//foo/") == "/home/foo"Common mistakes and edge cases
- Problem-specific boundary: Attempts to move above root have no effect; repeated slashes are ignored.
- Pattern-level pitfall: Check emptiness before reading the top and decide whether an operator, delimiter, or node is consumed before or after the pop.
- Invariant check: after every update, confirm that the stack is the canonical absolute path for all processed components.
Interview review checklist
- Explain why canonical path stack matches the structure of this input.
- State the invariant in one sentence before tracing code: The stack is the canonical absolute path for all processed components.
- Derive O(n) time and O(n) space from how many times each element or state is visited.
- Test the boundary explicitly: Attempts to move above root have no effect; repeated slashes are ignored.
Browse the searchable 100 LeetCode Python Solutions hub. Previous: 20. Valid Parentheses · Next: 155. Min Stack