Simplify Path
Expert Answer & Key Takeaways
A complete guide to understanding and implementing Stack.
Simplify Path
Given a Unix-style absolute path, simplify it to its canonical form.
Visual Representation
path = "/home//foo/../bar/"
Tokens: ["home", "", "foo", "..", "bar"]
1. "home": Valid name. Push. Stack: ["home"]
2. "": Empty. Skip.
3. "foo": Valid name. Push. Stack: ["home", "foo"]
4. "..": Parent dir. Pop. Stack: ["home"]
5. "bar": Valid name. Push. Stack: ["home", "bar"]
Canonical Path: "/home/bar"Examples
Input: path = "/home//foo/"
Output: "/home/foo"
Input: path = "/../"
Output: "/"
Approach 1
Level I: Iterative Stack Processing (Natural Approach)
Intuition
Split the path by '/' into parts. Maintain a list acting as a stack: push valid directory names, pop for '..', skip '.' and empty parts. Join the stack with '/' prefixed by '/'.
⏱ O(N)💾 O(N)
Approach 2
Level II: Recursive Path Reduction
Intuition
Instead of using an explicit stack, we can process the path string repeatedly by removing the most 'reducible' parts. For example, replacing
/./ with / and /directory_name/../ with /. This is less efficient but helpful for understanding the underlying LIFO structure of the path.⏱ O(N^2) in the worst case (e.g., /a/a/a/a/../../../../)💾 O(N) for string copies during reduction.
Approach 3
Level III: Optimal (Stack Tokenization)
Intuition
Split the path by
/ and process each component. A stack maintains the valid directory structure. .. removes the last added directory, while . or empty strings are ignored. Any other string is a valid directory to be pushed.⏱ O(N)💾 O(N)
Detailed Dry Run
| Part | Action | Stack Content |
|---|---|---|
| "home" | Push | ["home"] |
| "foo" | Push | ["home", "foo"] |
| ".." | Pop | ["home"] |
| "bar" | Push | ["home", "bar"] |
⚠️ Common Pitfalls & Tips
Multiple slashes become one.
.. at the root keeps you at the root. The trailing slash should be removed unless it's the root itself.Course4All Technical Board
Verified ExpertSenior Software Engineers & Algorithmic Experts
Our DSA content is authored and reviewed by engineers from top tech firms to ensure optimal time and space complexity analysis.
Pattern: 2026 Ready
Updated: Weekly
Found an issue or have a suggestion?
Help us improve! Report bugs or suggest new features on our Telegram group.